SwiftUI LazyVGrid and LazyHGrid

Keerthiraj Su
2 min readJan 9, 2022

Lazy grids is an easy way to put items on screen. For example if we look Facebook or Instagram we can see how these items are arranged.

There are lot of different ways we can customise rows and columns, so layouts are dynamic and adapt to different devices.

All the grids are lazy by layout. They are made up of 3 different things

  1. An array of grid items that describe the layout
  2. The type of grid(LazyVGrid and LazyHGrid)
  3. The data(model) to populate the grid

Note: Here lazy means only items which are on screen are persistent. If there are 100 items then only those items on the screen are created, and these grids are lazy by default.

LazyVGrid:

These are used to make a Vertically scrolling grid, it accepts coloumns in its initializer.

struct LearnGrid: View {    let columnGrid = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
LazyVGrid(columns: columnGrid) {
ForEach(0..<100) { index in
Circle()
.frame(height: 100)
}
}.padding(10)
}
}

Here coloumnGrid describes gridLayout. 3 columns with flexible size. We have different option to specify size: .fixed(), .flexible(). adaptive().

  1. GrindItem(.fixed())… lets you specify the item to specific size.
  2. GrindItem(.flexible())… lets you specify how big each item should be. So that it can be defined while creating the item as shown in example above
  3. GrindItem(.adaptive(50))means we want the grid to fit in as many items per row as possible, using a minimum size of 50 points each.

LazyHGrid:

These are used to make a horizontally scrolling grid, which works in much the same way except it accepts rows in its initializer.

struct LearnGrid: View {    let rowGrid = [
GridItem(.flexible()),
GridItem(.flexible()),
GridItem(.flexible())
]
var body: some View {
LazyHGrid(rowGrid: columnGrid) {
ForEach(65..<91, id:\.self) { index in
Text(String(Unicode.Scalar(index)!))
}
}.padding(10)
}
}

In above example we are print alphabets in a horizontal grid.

Note:

Using \.self tells Swift each item is uniquely identified using its own value. So, if you have the array [1, 2, 3] and identify each value by \.self it means the first item has the identifier 1, the second 2, and the third 3

We can combine these grid in a scroll view and build our view below is an example:

Keep coding..

--

--