When SwiftUI was presented for the first time, it wasn’t supporting grid view by default. Of course, you could do this by yourself, but there were not any tools to make this process easier. This is why many frameworks for packages imitating the UICollectionView appered very quickly after SwiftUI's release.

QGrid

One of these is QGrid, a very easy-to-use Grid View for SwiftUI. QGrid splits Grid View into 2 configurations:

  • implementation in your SwiftUI file,
  • view for single grid cell.

So first, you need to build your cell with VStack or HStack. Then during implementation, you decide how many columns will be displayed in grid.

For example: struct MyView: View { var body: some View { QGrid(myList, columns: 3) { GridCell(person: $0) } } }

QGrid is great for simple display of Grid View, i.e. without custom changes. Of course, you can customize how QGrid will lay out cells, but there are no more features. So before using QGrid you should decide, whether it really fits your app.

iOS 14 SwiftUI Grid

But right now, with iOS 14 we have an easier way to implement Grid View in our apps. Let me introduce Lazy Grid. „Lazy” means that the grid view does not create items until they are needed.

First, we need to determine columns for our Grid View. It can look like this:

    let columns = [
        GridItem(.fixed(100.0), spacing: 20.0, alignment: .leading),
        GridItem(.fixed(100.0), spacing: 20.0, alignment: .leading),
        GridItem(.fixed(100.0), spacing: 20.0, alignment: .leading),
    ]

Then we need to set our Grid in our SwiftUI View. No need to mention that placing it inside ScrollView is a good practice, right?

            ScrollView(.vertical) {
                LazyVGrid(columns: columns, alignment: .center) {
                    ForEach(0..<myList.count) { index in
                        let item = presenter.bookList[index]
                        GridCell(item: item)
                    }
                }
            }

Of course, we can use Lazy Grid if we need to place cells horizontally. Lazy Grid has other limitations. The main one is that it can be used only with iOS 14. So if you want to build your app for older iOS versions, using one of the available frameworks like QGrid, is a better way to go.