Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Build a Grid of Views in SwiftUI
Written by Team Kodeco

In many cases, you may want to display a collection of views in a grid format, such as a photo gallery or a game board. Fortunately, SwiftUI makes it easy to build a grid of views by using the LazyVGrid or LazyHGrid view.

Here’s an example of how to create a grid of views in SwiftUI:

struct ContentView: View {
  let items = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
  let columns = [
    GridItem(.flexible()),
    GridItem(.flexible()),
    GridItem(.flexible())
  ]

  var body: some View {
    LazyVGrid(columns: columns, spacing: 16) {
      ForEach(items, id: \.self) { item in
        Text(item)
          .frame(maxWidth: .infinity)
          .frame(height: 100)
          .background(.blue)
          .foregroundColor(.white)
      }
    }
    .padding()
  }
}

The preview for this view should now look as follows:

An example of a grid in SwiftUI.
An example of a grid in SwiftUI.

In this example, you begin by creating an array of items to display in the grid. You then define a columns array that sets up the layout of the grid. In this case, you use three columns that have a flexible size.

The LazyVGrid view is used to create the grid layout. You pass in the columns array to the columns parameter, and you specify the spacing between the grid items.

Inside the LazyVGrid, you use a ForEach loop to iterate over each item in the items array. You use the .self identifier to specify that you want to use the item string as the identifier for each item in the loop.

Inside the ForEach loop, you create a Text view that displays each item string. You use the frame modifier to give the view a flexible width and a fixed height of 100 points. You also set the background color to blue and the foregroundColor to white to make the text easier to read.

Finally, you add some padding to the edge of the grid using the padding modifier.

With this code example, you now know how to build a grid of views in SwiftUI using the LazyVGrid view. By customizing the columns array and the spacing parameter, you can create a variety of different grid layouts to fit the needs of your app.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.