In SwiftUI, when do you choose Grid with GridRow over LazyVGrid, and what does each container give up?
answer
- eager versus lazy
- who knows the widest cell
- spanning and column alignment
- profile before going lazy
basics
~20 sGrid creates every cell up front, so it sizes columns to their widest cell, aligns cells across rows and supports spanning; LazyVGrid creates cells only as needed, which scales to long collections but needs columns described in advance.
solid answer
~40 s`Grid` with `GridRow` (iOS 16) creates all of its cells immediately, so it can make each column as wide as its widest cell, each row as tall as its tallest, align a whole column with `gridColumnAlignment(_:)`, and span cells with `gridCellColumns(_:)`. That makes it right for table-like content such as a recipe's nutrition facts. `LazyVGrid` creates cells only when they're needed, so it suits a long, data-driven wall of recipe cards, but because most cells don't exist yet it relies on `GridItem` sizes and has no spanning. Apple's advice is to start with `Grid` and switch to a lazy grid only when profiling shows a large scrolling grid is slow. Neither scrolls on its own, so both go in a `ScrollView` when they can overflow.
code
swift · 24 linesimport SwiftUI
struct NutritionTable: View {
var body: some View {
Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 12, verticalSpacing: 8) {
GridRow {
Text("Calories")
.gridColumnAlignment(.trailing)
Text("420 kcal")
}
GridRow {
Text("Protein")
Text("32 g")
}
Divider()
.gridCellUnsizedAxes(.horizontal)
GridRow {
Text("Serves 4, about 35 minutes")
.gridCellColumns(2)
}
}
.padding()
}
}go deeper
Recall that Grid is built from GridRow rows and creates all cells at once, while LazyVGrid creates cells only as they are needed.
Explain how Grid sizes columns and rows from its cells, what gridCellColumns and gridColumnAlignment do, and why a lazy grid cannot offer the same.
Show you would choose by content shape and measured cost, and that you can debug a grid that unexpectedly fills the screen or misaligns a spanning cell.
Be ready to explain to a team why the eager container is the default and what profiling evidence justifies moving a screen to a lazy grid.
## Two containers for two jobs SwiftUI has two kinds of two-dimensional container. `Grid`, added in iOS 16 together with `GridRow`, is a **static** container: you write its rows, and it creates all of its child views immediately. `LazyVGrid` and `LazyHGrid`, available since iOS 14, are **lazy** containers: you describe the columns (or rows) with `GridItem` values, hand them a collection of items, and they create each cell only when SwiftUI needs to display it. That single difference, eager versus lazy, explains almost every trade-off between them. ## What Grid can do because it sees every cell Apple describes a grid as behaving something like a set of `HStack` rows inside a `VStack`, with one crucial difference: it handles rows and columns as a single operation, so alignment and spacing apply to cells rather than to rows and then to a column of unrelated rows. Concretely: - **Column count** grows to match the row with the most cells; shorter rows get empty cells on their trailing edge. - **Column width** matches the widest cell in the column, and **row height** matches the tallest cell in the row. - **Spanning**: a view placed in the grid outside any `GridRow` spans all columns, and `gridCellColumns(_:)` makes a cell inside a row span a given number of columns. - **Alignment**: `Grid(alignment:horizontalSpacing:verticalSpacing:content:)` sets a default for every cell, `GridRow(alignment:)` overrides vertical alignment for a row, `gridColumnAlignment(_:)` on one cell sets the horizontal alignment of its whole column, and `gridCellAnchor(_:)` positions a single cell with a unit point. - **Row modifiers fan out**: a modifier on a `GridRow` applies to each cell, like a `Group`, so a `border` on a row draws a border around every cell. Those features are what a table-shaped layout needs: the nutrition facts on a recipe page, a form whose labels line up, a scoreboard. ## What LazyVGrid gives you instead A lazy grid fills its columns row after row from data, so a `ForEach` over hundreds of recipes only pays for the cells on screen. The price is precision. It cannot size a column from its widest cell, because most cells don't exist yet, so the `GridItem` array must describe each column up front. It has no column spanning and none of the per-column alignment modifiers listed above. ## Side by side | | `Grid` with `GridRow` | `LazyVGrid` | |---|---|---| | Creates cells | all at once | as SwiftUI needs to display them | | Column widths | from the widest cell | from `GridItem` sizes | | Column count | the widest row | item count, or adaptive | | Spanning | `gridCellColumns(_:)`, views outside rows | none | | Column alignment | `gridColumnAlignment(_:)` | per-item `alignment` | | Best for | small, table-like content | long, data-driven collections | | Available since | iOS 16 | iOS 14 | Neither container scrolls by itself; put either one in a `ScrollView` when it can outgrow the screen. ## Apple's guidance on choosing Apple's documentation is direct about the default: use `Grid`, and **switch to a lazy grid only if profiling shows a worthwhile improvement**, typically when a large grid inside a `ScrollView` is slow to appear. For a recipe browser the split is natural: the scrolling wall of recipe cards is a `LazyVGrid`, and the ingredient and nutrition table on the detail screen is a `Grid`. ## Traps when you build a Grid 1. **A flexible cell widens the whole grid.** A `Divider`, `Spacer` or `Color` takes all the space it is offered, so a divider between rows stretches the grid to its parent's full width. Add `.gridCellUnsizedAxes(.horizontal)` to stop it claiming extra width. 2. **`EmptyView` does not make a blank cell.** It resolves to the absence of a view. Use `Color.clear`, with `gridCellUnsizedAxes(_:)` so it doesn't grow. 3. **Conflicting column alignment.** Apply `gridColumnAlignment(_:)` to one cell per column; Apple documents undefined behavior if different cells in the same column ask for different alignments. 4. **Merged cells align differently.** A cell that spans several columns switches to anchor alignment instead of the usual alignment guides; adjust it with `gridCellAnchor(_:)`. If you need a grid as one option of a layout that switches at runtime, `GridLayout` is the version of `Grid` that conforms to the `Layout` protocol; switching layouts that way is covered with custom layout containers.
- How do you leave a cell blank in a SwiftUI Grid?Put an invisible view in the slot, usually `Color.clear`, and add `gridCellUnsizedAxes(_:)` so the flexible color doesn't claim more space than the other cells need. `EmptyView` doesn't work: Apple's documentation notes it resolves to the absence of a view, so it creates no cell and the following views shift left by one column.
- What happens if two cells in the same Grid column use different gridColumnAlignment values?Apple documents the result as undefined behavior. The modifier sets the alignment for the whole column, so it belongs on exactly one cell in that column, conventionally the first row; the grid then aligns every cell in the column the same way.
- Why might a cell with gridCellColumns(2) not line up with the alignment guides used by the other cells?When a cell spans several columns, the grid can't pick one column's horizontal guide, so it converts the grid's alignment into a unit-point anchor for the merged cell and uses anchor alignment instead. The cell is positioned within the merged area by that anchor; you change it with `gridCellAnchor(_:)` rather than with alignment guides.
- Grid is just a VStack of HStacks with no shared column widths.
- LazyVGrid should be the default for every grid because lazy is always faster.
- An EmptyView inside a GridRow makes a blank cell.
- A border on a GridRow draws one border around the whole row.
- A Grid scrolls on its own when its rows overflow the screen.