30
loading...
This website collects cookies to deliver better user experience
LazyVGrid
and LazyHGrid
. This time, we will dig deeper and understand how we can use these components. The great thing about these two components is their usage; views are loaded lazily, which means when those appear on the screen.HStack
and VStack
are available from iOS 14 and upward. If you're going to use grid layout in iOS 13, you should look into HStack
and VStack
, but the drawback is that those don't support lazy loading.LazyVGrid
is done by providing the columns, alignment of the items, spacing between the items, pinned views to the footer or header, and the content itself.var columns = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 20, pinnedViews: .sectionHeaders) {
Section(header: Text("Smilies").font(.title),
footer: Text("Emoji smilies").font(.subheadline)) {
ForEach(Emoji.smilies, id: \.self) { emoji in
Text(emoji)
.font(.largeTitle)
}
}
Section(header: Text("Animals").font(.title),
footer: Text("Emoji animals").font(.subheadline)) {
ForEach(Emoji.animals, id: \.self) { emoji in
Text(emoji)
.font(.largeTitle)
}
}
Section(header: Text("Food").font(.title),
footer: Text("Emoji food").font(.subheadline)) {
ForEach(Emoji.food, id: \.self) { emoji in
Text(emoji)
.font(.largeTitle)
}
}
}
.padding(.horizontal)
}
}
LazyHGrid
, it is pretty similar. We just need to exchange columns
parameter to `rows.GridItem
. Grid item is either row or column.GridItem,
these three parameters are vital:size
- size of the item;spacing
- spacing between the items;alignment
- alignment when placing each grid item.flexible(minimum: CGFloat, maximum: CGFloat)
- single flexible item in available space with optional parameters for min and max size;adaptive(minimum: CGFloat, maximum: CGFloat)
- multiple items in available space;fixed(CGFloat)
- single item with a fixed size in available space.LazyVGrid
and LazyHGrid
.
swift
[
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
[
GridItem(.adaptive(minimum: 50))
]
GridItem
layout size is meant to use when we know the item size, and it is constant.[
GridItem(.fixed(100)),
GridItem(.fixed(100)),
GridItem(.fixed(100))
]
LazyVGrid
and LazyHGrid
.