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.

Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

Let's look at an example.

var body: some View {
Grid(horizontalSpacing: 20, verticalSpacing: 20) {
ForEach(animals, id: \.name) { animal in
GridRow(alignment: .top) {
Text(animal.name)
.gridColumnAlignment(.trailing)
Image(systemName: animal.imageSystemName)
.gridColumnAlignment(.center)
Text(animal.description)
.gridColumnAlignment(.leading)
}
}
}.padding()
}

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.

Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swiftui

swift

ios

How to manage lifecycle events in SwiftUI iOS applications

Discover SwiftUI's lifecycle events onAppear(), onDisappear() and task().

26 Sep 2022 · 3 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum