How to create a scrollable grid in SwiftUI using LazyHGrid
The above layout may seem pretty easy to achieve -and, trust me, it is. At first, however, I struggled a bit to get it right.
The symbols I’m using in this tutorial are SFSymbols.
I found two ways of achieving the above layout: using a LazyHGrid and using a HStack. Spoiler alert: the latter is the best BUT I’ll show you both anyway.
LazyHGrid solution — (not recommended)
In order to recreate the grid, we need to put a LazyVGrid inside a ScrollView with .horizontal direction. It’s necessary to specify this because the default value is .vertical.
The key points you shouldn’t forget in order to achieve this result are:
- setting the Grid Item’s size to .flexible();
- adding .fixedSize() to the LazyHGrid so that its size depends on the cells’ size. If you don’t the grid will use more screen space than necessary;
HStack solution — (recommended)
However you should also be aware that the LazyHGrid one isn’t the best approach to the problem. The correct (and easier) procedure would be using a ScrollView with a HStack:
That’s pretty much all.
If you enjoyed my article, please clap and subscribe!