Chapter 44
Creating Grid Layout Using Grid APIs

SwiftUI introduced a new Grid API for composing grid-based layout along with the release of iOS 16. While you can arrange the same layout using VStack and HStack, the Grid view makes it a lot easier. A Grid view is a container view that arranges other views in a two-dimensional layout.

The Basics

Let's start with a simple grid. To create a 2x2 grid, you write the code like below:

struct ContentView: View {
    var body: some View {
        Grid {
            GridRow {
                Color.purple
                Color.orange
            }

            GridRow {
                Color.green
                Color.yellow
            }
        }
    }
}

Assuming you've created a SwiftUI project in Xcode, you should see a 2x2 grid, filled with different colors.

Figure 1. A basic grid
Figure 1. A basic grid

To create a 3x3 grid, you just need to add another GridRow. And, for each GridRow, you insert one more child view.

Figure 2. A 3x3 grid
Figure 2. A 3x3 grid

Comparing Grid Views and Stack Views

To access the full content and the complete source code, please get your copy at https://www.appcoda.com/swiftui.

results matching ""

    No results matching ""