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.
Wrap rows in a Grid container
Grid is the outermost layout view; you give it a
@ViewBuildercontent closure and declare each horizontal line of cells inside. HereGrid { ... }contains the entire table, and SwiftUI scans every row to compute a shared column geometry before laying anything out.Define each row with GridRow
A
GridRowgroups the views that occupy a single row, and each view in the closure becomes one cell in successive columns. The example declares threeGridRowblocks — a header withText("Name")andText("Score"), then data rows forText("Alice")/Text("92")andText("Bob")/Text("87")— so the two columns stay aligned down the whole grid.Control gaps with horizontalSpacing and verticalSpacing
The initializer
Grid(horizontalSpacing:verticalSpacing:)sets the distance between columns and between rows. PassinghorizontalSpacing: 12andverticalSpacing: 12gives an even 12-point gutter on both axes; omit either argument to fall back to the platform default spacing.Place full-width content outside a GridRow
A view written directly in the Grid's closure rather than inside a
GridRowspans all columns instead of occupying a single cell. The bareDivider()between the header and the data takes advantage of this, drawing a separator line across the entire width of the grid.
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.
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()
}
}