Finally, SwiftUI supports Grids natively
WWDC 2020 just happend and with it iOS 14 was announced, bringing new features such as the a new Grid system called LazyHStack and LazyVStack .
At the current time, it’s not advised to switch to iOS14 and should wait for a few months for adoption, but this is a great addition to SwiftUI, as before we’d have to implement a computed grid with GeometryReader and is not very performant.
The prefix means that the content is lazy loaded (only when required) and not all in advance.
LazyVGrid works vertically (from top to bottom), the rows are added when the cells at the top row are filled.
struct VerticalGrid: View {
var data: [GridItem] = Array(repeating: .init(.flexible()), count: 3)
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
LazyVGrid(columns: data, alignment: .center, spacing: 8)
{
ForEach(0 ..< 22) { number in
Text("\(number)")
.font(.title)
.frame(height: 50)
.frame(maxWidth: .infinity)
.background(number.isEven ? Color.black : Color.blue)
}
}
}
}
}
LazyHGrid works horizontally, from left to right. The views are included one below the other, and when the column is filled, LazyHGrid adds another one to the right.
struct HorizontalGrid: View {
var rows: GridItem = Array(repeating: .init(.flexible()), count: 5)
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: rows, alignment: .center, spacing: 8) {
ForEach(0 ..< 21) { number in
Text("\(number)")
.font(.title)
.frame(width: 100)
.frame(maxHeight: .infinity)
.background(number.isEven ? Color.black : Color.blue)
}
}
}
}
}
This might be a bit confusing, but think about the “Grid” as a while that either grows “top to bottom” or “left to right”.
The GridItem defines the behavior and size of the cells. When created we can pass the following arguments (size, spacing, alignment).