TechnologiesSwiftUI

GridLayout struct

iOSmacOStvOSwatchOSvisionOSiOS 16.0+✓ renders

A grid that you can use in conditional layouts.

How it works

GridLayout is the layout type that backs SwiftUI's Grid container, arranging child views into a two-dimensional grid whose columns automatically align across every row. Reach for it when you have tabular content — forms, comparison tables, keypads — where cells in the same column should share a width without you computing those widths by hand. Unlike a stack of HStacks, a Grid measures all of its rows together, so the second column of one row lines up with the second column of the next.

  1. Declare the container with Grid

    A Grid establishes the grid coordinate space and adopts GridLayout to position its children. You build one with a trailing closure of rows, as in the Grid that wraps the GridRow entries here; everything inside participates in the shared column alignment.

  2. Define each row with GridRow

    Each GridRow groups views into a single horizontal line of cells, and the Nth view in every row becomes the Nth column. The three GridRow blocks — the header, Text("Alice")/Text("92"), and Text("Bob")/Text("87") — each contribute two cells, so the grid resolves to two aligned columns.

  3. Set the gutters with horizontalSpacing and verticalSpacing

    The Grid initializer takes horizontalSpacing and verticalSpacing to control the gaps between columns and between rows. Passing horizontalSpacing: 12, verticalSpacing: 12 gives the cells uniform breathing room without inserting spacer views.

  4. Span columns with views placed directly in the Grid

    A view placed in the Grid body but outside a GridRow is laid out across the full width of all columns. The Divider() sits between rows and stretches the entire grid width, separating the header from the data without you specifying a column count.

Try it — Add a third Text to the header GridRow (for example Text("Rank").bold()) and watch the grid grow to three aligned columns even though the data rows still have two cells.

Example & preview

Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.

GridLayout.swift
struct GridLayoutDemo: View {
    var body: some View {
        Grid(horizontalSpacing: 12, verticalSpacing: 12) {
            GridRow {
                Text("Name").bold()
                Text("Score").bold()
            }
            Divider()
            GridRow {
                Text("Alice")
                Text("92")
            }
            GridRow {
                Text("Bob")
                Text("87")
            }
        }
        .padding()
    }
}
Live preview
Name Score Alice 92 Bob 87
Name Score Alice 92 Bob 87
swift → lexer → parser → sema → uiir → canvas Open in Studio ↗
What's new in SwiftUI 27 →