LazyGridView in SwiftUI
In the SwiftUI, we have LazyVGrid and LazyHGrid to create collectionView. One is for creating a vertical grid and the other is for a horizontal grid. The word Lazy, as mentioned by Apple, means that the grid view does not create items until they are needed.
Decide how many columns should have in the grid?
> We have an array of GridItem, that describes how the grid looks like.
Like want 2-column:
let twoColumnGrid = [GridItem(.flexible()), GridItem(.flexible())]
Like want 3-column:
let threeColumnGrid = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]
OtherWay to create an Array of GridItem
let threeColumnGrid: [GridItem] = Array(repeating: GridItem(.flexible()), count: 3)
A simple code to create LazyGridView
if you want to build a horizontal grid, you use LazyHGrid like this:
Using GridItem to Vary the Grid Layout
Flexible
The flexible size type enables you to create three columns with equal size. If you want to describe a 3-column grid, you can create the array of GridItem
like this:
Adaptive
private var gridItemLayout: [GridItem] = [GridItem(.adaptive(minimum: 90))]
Adaptive size behavior in iPhone and iPad
Fixed
if you want to create fixed width columns. For example, a width of 100 points and the second one has a width of 150 points. You write the code like this:
private var gridItemLayout: [GridItem] = [GridItem(.fixed(100)), GridItem(.fixed(150))]
Fixed and Adaptive
Mix different size types to create more complex grid layouts.
var gridItemLayout = [GridItem(.fixed(100)),GridItem(.adaptive(minimum: 50))]
In this case, LazyVGrid
creates a fixed size column of 100 point width. And then, it tries to fill as many items as possible within the remaining space.
Source code:
GitHub Link: https://github.com/Nirajpaul2/LazyGridViewExample