TechnologiesSwiftUI

Grid struct

iOSmacOStvOSwatchOSvisionOSiOS 16.0+✓ renders

A container view that arranges other views in a two dimensional layout.

How it works

Grid is a container view that arranges its child views in a two-dimensional layout, aligning them into consistent columns and rows. Unlike nesting an HStack inside a VStack, a Grid measures all of its rows together, so cells in the same column share a width and line up cleanly across rows. Reach for Grid when you need tabular structure — forms, data tables, or any content where elements must align both horizontally and vertically.

  1. Wrap rows in a Grid container

    Grid is the outermost layout view; you give it a @ViewBuilder content closure and declare each horizontal line of cells inside. Here Grid { ... } contains the entire table, and SwiftUI scans every row to compute a shared column geometry before laying anything out.

  2. Define each row with GridRow

    A GridRow groups the views that occupy a single row, and each view in the closure becomes one cell in successive columns. The example declares three GridRow blocks — a header with Text("Name") and Text("Score"), then data rows for Text("Alice")/Text("92") and Text("Bob")/Text("87") — so the two columns stay aligned down the whole grid.

  3. Control gaps with horizontalSpacing and verticalSpacing

    The initializer Grid(horizontalSpacing:verticalSpacing:) sets the distance between columns and between rows. Passing horizontalSpacing: 12 and verticalSpacing: 12 gives an even 12-point gutter on both axes; omit either argument to fall back to the platform default spacing.

  4. Place full-width content outside a GridRow

    A view written directly in the Grid's closure rather than inside a GridRow spans all columns instead of occupying a single cell. The bare Divider() between the header and the data takes advantage of this, drawing a separator line across the entire width of the grid.

Try it — Add a third Text to each GridRow (for example Text("Rank") in the header and Text("1"), Text("2") in the data rows) and watch Grid grow to three aligned columns automatically.

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.

Grid.swift
struct GridDemo: 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 →