A SwiftUI recipe browser must show two columns on iPhone, five in iPad landscape and one at the largest text sizes; how do you build it?
answer
- width and text size, not the device
- size class cannot see orientation on iPad
- adaptive minimum or a measured count
- isAccessibilitySize collapses to one column
basics
~20 sDerive the columns from the grid's actual width, with adaptive GridItems or a count computed from a measured width, and switch to one column when dynamicTypeSize.isAccessibilitySize is true; device checks and size classes cannot tell iPad portrait from landscape.
solid answer
~40 sI treat the spec as two signals, width and text size, rather than devices. Checking for an iPad breaks in Split View, and `horizontalSizeClass` is typically `.regular` in both orientations on a full-screen iPad, so neither gives five columns in landscape. If the designer can accept a target card width, one `GridItem(.adaptive(minimum:maximum:))` lets the count follow the width. If five is a hard requirement, I measure the grid's width with `onGeometryChange(for:of:action:)` and compute `min(5, max(2, Int(width / 220)))` flexible columns. Then I read `@Environment(\.dynamicTypeSize)` and return a single column when `isAccessibilitySize` is true. I keep one `LazyVGrid` and change its columns array, and I test rotation, Split View, Slide Over and accessibility text sizes.
code
swift · 36 linesimport SwiftUI
struct RecipeBrowser: View {
@Environment(\.dynamicTypeSize) private var dynamicTypeSize
@State private var gridWidth: CGFloat = 0
private let inset: CGFloat = 16
let titles: [String]
private var columnCount: Int {
if dynamicTypeSize.isAccessibilitySize { return 1 }
let usable = gridWidth - 2 * inset
return min(5, max(2, Int(usable / 220)))
}
var body: some View {
ScrollView {
LazyVGrid(
columns: Array(repeating: GridItem(.flexible(), spacing: 16), count: columnCount),
spacing: 16
) {
ForEach(titles, id: \.self) { title in
Text(title)
.font(.headline)
.frame(maxWidth: .infinity, minHeight: 140)
.background(.quaternary, in: RoundedRectangle(cornerRadius: 12))
}
}
.padding(inset)
}
.onGeometryChange(for: CGFloat.self) { proxy in
proxy.size.width
} action: { newWidth in
gridWidth = newWidth
}
}
}go deeper
Recall that size classes, Dynamic Type size and the grid's own width are separate inputs a SwiftUI view can read.
Explain how adaptive GridItems change the column count with width and how isAccessibilitySize identifies the five accessibility text sizes.
Show you can spot that the spec mixes device language with width, choose between adaptive columns and a measured count, and verify across rotation, multitasking and text sizes.
Be ready to negotiate the spec itself: a stable card width usually serves users better than per-device column counts and leaves less code to maintain.
## Translate the requirement into signals "Two columns on iPhone, five in iPad landscape, one at the largest text sizes" reads like three device rules, but none of them is really about the device. Two are about **width** and one is about **text size**: | Requirement | What actually varies | SwiftUI input | |---|---|---| | two columns on iPhone | a narrow width | the width the grid gets | | five on iPad in landscape | a wide width | the width the grid gets | | one column at the largest text sizes | the Dynamic Type setting | `dynamicTypeSize.isAccessibilitySize` | Framing it this way avoids the most common wrong answer. ## Why the device and the size class are the wrong inputs - **The device** never changes, but the window does. An iPad app in a narrow Split View or Slide Over window is about as narrow as an iPhone and needs the two-column layout; a check for "is this an iPad" gives it five squeezed columns. - **The horizontal size class** handles that case, since a narrow iPad window typically reports `.compact`, but it is a two-value bucket. A full-screen iPad typically reports `.regular` in both orientations, so the size class cannot tell portrait from landscape, nor a smaller iPad from a larger one. The size class is still right for structural choices on the same screen, such as a filter panel beside the grid versus a filter sheet. It is the wrong input for counting columns. ## Option 1: let adaptive columns follow the width `GridItem(.adaptive(minimum:maximum:))` fits as many cells of at least `minimum` points as the row allows and stretches them toward `maximum`. Rotation, Split View and window resizing all just change the width, and the column count follows. The catch is that **you no longer choose the count**: a minimum small enough for two columns on the narrowest iPhone you support may give six or more on a large iPad in landscape. Often a stable card width is what the designer actually wants, so this is worth proposing before writing any measuring code. ## Option 2: derive an exact count from the width When the count itself is the requirement, measure the width the grid really gets and compute it: - `onGeometryChange(for:of:action:)`, available from iOS 16, reports the width into a `@State` property without wrapping the screen in a `GeometryReader` (reading geometry is covered in its own lesson). - Divide by a target card width and clamp: `min(5, max(2, Int(width / 220)))` yields two on an iPhone and up to five on a wide iPad. - Build the columns as `Array(repeating: GridItem(.flexible(), spacing: 16), count: count)`. - Remember that the measured width includes any padding you place inside it; subtract it, or measure the view the padding wraps. ## The accessibility rule Read `@Environment(\.dynamicTypeSize)`. `DynamicTypeSize` is ordered, and Apple's documentation singles out the five sizes whose names begin with `accessibility` as much larger than the rest; `isAccessibilitySize` lets you change a layout for exactly those sizes without comparing values yourself. When it is true, return a single flexible column so each card gets the full width for its wrapped title. Inside each card, a `ViewThatFits` can also flip the metadata row from side by side to stacked. ## Keep one grid and change its columns Compute the columns array and pass it to a single `LazyVGrid`. Writing `if`/`else` between two separate grid views would make SwiftUI replace one view with another and discard its state, while changing an input of the same view updates it in place. No layout switching is needed when only the column count changes. ## Verifying it 1. Preview the screen at the default text size and at an accessibility size. 2. Rotate an iPad and check the column count in portrait and in landscape. 3. Open the app in Split View and Slide Over and confirm the narrow window gets two columns. 4. Where the iPad supports free window resizing, drag the window edge and watch the count step up and down. 5. Run on the narrowest iPhone you support and confirm two readable columns remain. ## Mistakes to avoid - **Reading the screen size once at launch.** The window changes with rotation and multitasking; derive the count from the width the view is given every time it changes. - **Hard-coding counts per device.** New screen sizes and resizable windows break every table of devices. - **Forgetting the text-size rule.** A five-column grid of truncated titles at an accessibility size fails the people who most need the content.
- What would you tell a designer who insists on exactly five columns on every iPad in landscape?That iPads differ in width and that multitasking makes the window width almost arbitrary, so a fixed count means very different card sizes. I'd show the layout on the smallest and largest iPad, then propose a target card width with a clamp on the count, which keeps cards readable everywhere and still gives about five columns on common landscape widths.
- Where does horizontalSizeClass still belong on this recipe screen?In structural decisions that genuinely follow the window class: for example, showing a filter panel beside the grid in a regular-width window and a filter sheet in a compact one. Those choices change what is on screen, not how many cards fit, so a two-value bucket is the right level of detail for them.
- Check whether the device is an iPad, then hard-code five columns.
- An iPad in landscape reports a different horizontal size class from portrait.
- Accessibility text sizes only need bigger fonts, not a different arrangement.
- Comparing dynamicTypeSize >= .xxxLarge is how you detect accessibility sizes.
- Read the screen size once at launch and choose the column count from it.