Created
March 10, 2023 17:43
-
-
Save devs-rootstrap/50b762c989058e419f904286e4247fcf to your computer and use it in GitHub Desktop.
Building faster scrollable views using LazyStacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Data Model & Arrray Example */ | |
struct Contact: Identifiable, Hashable { | |
let id = UUID() | |
let firstName: String | |
let lastName: String | |
let shortName: String | |
let role: String | |
let phone: String | |
var name: String { | |
firstName + " " + lastName | |
} | |
} | |
/* Fill the array with the number of contact that you want to display, in this example we have defined only 1 */ | |
let contacts : [Contact] = [ | |
Contact(firstName: "Aaron", lastName: "Smith", shortName: "AS", role: "Software Engineer", phone: "2313233268") | |
] | |
/* ScrollView with LazyHStack component example */ | |
ScrollView(.horizontal) { | |
LazyHStack(alignment: .top, spacing: 10) { | |
ForEach(contacts, id: \.self) { contact in | |
VStack(alignment: .center) { | |
ZStack { | |
Circle() | |
.fill(colors.randomElement()!) | |
.frame(width: 90, height: 90) | |
Text(contact.shortName) | |
.foregroundColor(.white) | |
.font(.system(size: 40, weight: .bold)) | |
} | |
VStack { | |
Text(contact.firstName) | |
Text(contact.lastName) | |
} | |
} | |
} | |
} | |
.padding() | |
} | |
.frame(height: 165) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var body: some View { | |
VStack { | |
Text("Contact example II") | |
.font(.title) | |
ScrollView() { | |
LazyVStack(alignment: .leading, spacing: 10) { | |
Section { | |
ForEach(contacts, id: \.self) { contact in | |
HStack(spacing: 10) { | |
ZStack { | |
Circle() | |
.fill(colors.randomElement()!) | |
.frame(width: 90, height: 90) | |
Text(contact.shortName) | |
.foregroundColor(.white) | |
.font(.system(size: 40, weight: .bold)) | |
} | |
VStack(alignment: .leading) { | |
Text(contact.name) | |
.font(.title2) | |
Text(contact.role) | |
} | |
} | |
.padding() | |
} | |
} footer: { | |
Text("\(contacts.count) contacts found") | |
.padding() | |
.frame(maxWidth: .infinity) | |
.foregroundColor(.white) | |
.background(.blue) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment