Logo for tanaschita.com

Quick guide on the Grid container in SwiftUI

Understanding how to use the Grid layout introduced at WWDC22.

20 Jun 2022 · 2 min read

At WWDC22, Apple introduced the new Grid container that arranges views in a two dimensional layout.

Since iOS 14 SwiftUI already provides lazy grids, LazyHGrid and LazyVGrid. Those are made for use cases where we want to show scrollable content. Both lazy containers are built for efficiency, they only load views that are visible or about to be presented. The downside is that a lazy container can't automatically size its cells in both dimensions.

And that's where the new Grid container comes in. Unlike a lazy grid, it loads all views at once, so we have more control over the layout of rows and columns.

Let's look at an example.

var body: some View {
Grid(horizontalSpacing: 20, verticalSpacing: 20) {
ForEach(animals, id: \.name) { animal in
GridRow(alignment: .top) {
Image(systemName: animal.imageSystemName)

The code above uses a Grid container and adds a GridRow to it for every list item in the animals list. Each row consists of a Text view, an Image view and another Text view whereas each of them is individually aligned with the gridColumnAlignment modifier. This results in the following view:

Grid container example.
Grid container example.

As shown in the example, the Grid container gives us multiple possibilities to control the alignment of rows and columns.

We can set the alignment for the whole grid container, for each row and also for each element inside a row. To be able to do that, a grid renders all of its child views immediately, so it is not suited for a scrollable large set of views. In this case, a LazyVGrid or LazyHGrid would provide a better performance.


Like to support my work?

Say hi

Related tags

Articles with related topics

Latest articles and tips