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.
Declare the container with Grid
A
Gridestablishes the grid coordinate space and adopts GridLayout to position its children. You build one with a trailing closure of rows, as in theGridthat wraps theGridRowentries here; everything inside participates in the shared column alignment.Define each row with GridRow
Each
GridRowgroups views into a single horizontal line of cells, and the Nth view in every row becomes the Nth column. The threeGridRowblocks — the header,Text("Alice")/Text("92"), andText("Bob")/Text("87")— each contribute two cells, so the grid resolves to two aligned columns.Set the gutters with horizontalSpacing and verticalSpacing
The
Gridinitializer takeshorizontalSpacingandverticalSpacingto control the gaps between columns and between rows. PassinghorizontalSpacing: 12, verticalSpacing: 12gives the cells uniform breathing room without inserting spacer views.Span columns with views placed directly in the Grid
A view placed in the Grid body but outside a
GridRowis laid out across the full width of all columns. TheDivider()sits between rows and stretches the entire grid width, separating the header from the data without you specifying a column count.
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.
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()
}
}