In SwiftUI, how do you adapt a screen's layout for iPad by reading horizontalSizeClass and verticalSizeClass from the environment?
answer
- two buckets per axis
- an environment value, not a device check
- changes with rotation and multitasking
- compact versus regular, and it is optional
basics
~20 sSwiftUI publishes horizontal and vertical size classes as environment values, each compact or regular; read them with @Environment, branch the layout on them, and expect them to change at runtime with rotation, Split View and Slide Over.
solid answer
~40 sI declare `@Environment(\.horizontalSizeClass) private var horizontalSizeClass` and switch the arrangement on it: a recipe browser shows two columns of cards when the value is `.compact` and a denser grid when it is `.regular`. The type is `UserInterfaceSizeClass?` with two cases, so I also pick a default for `nil`. SwiftUI sets it from the device type, the orientation and iPad multitasking, so an iPad app in a narrow Split View or Slide Over window reports a compact width, like an iPhone. It can change while the app runs, and the view simply re-renders with the new value; I never check whether the device is an iPad instead. Because it is only a two-value bucket, I use it for structural switches and let adaptive grid columns or `ViewThatFits` handle exact widths.
code
swift · 26 linesimport SwiftUI
struct Recipe: Identifiable {
let id: UUID
let title: String
}
struct RecipeBrowser: View {
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
let recipes: [Recipe]
private var columnCount: Int {
horizontalSizeClass == .regular ? 4 : 2
}
var body: some View {
ScrollView {
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: columnCount)) {
ForEach(recipes) { recipe in
Text(recipe.title)
}
}
.padding()
}
}
}go deeper
Recall the @Environment key paths, the two cases compact and regular, and that the value updates when the device rotates or the iPad window is resized.
Explain what sets the value, including Split View and Slide Over, why it is optional, and why a size class drives structure rather than exact column counts.
Show you would replace device checks with size classes, keep stateful views outside the branch that switches, and test rotation and multitasking before release.
Be ready to argue which screen-level decisions a team should key on size classes and which belong to flexible layout, so iPad support does not become a fork of every screen.
## What a size class is A **size class** is SwiftUI's coarse description of how much room a view has in one direction. The `UserInterfaceSizeClass` enum has exactly two cases, `.compact` and `.regular`, and SwiftUI publishes one value per axis through the environment: `horizontalSizeClass` and `verticalSizeClass` on `EnvironmentValues`. Both are declared as optionals (`UserInterfaceSizeClass?`), so code that reads them should decide what a missing value means. The value is **not a width in points**. It is a bucket that says whether the view lives in a constrained space or a roomy one, which is the right level of detail for structural decisions: one column or two panes, a sheet or an inline panel, a toolbar of icons or a toolbar of labelled buttons. ## Reading it in a view You read a size class like any other environment value, with the `@Environment` property wrapper and a key path: ```swift @Environment(\.horizontalSizeClass) private var horizontalSizeClass @Environment(\.verticalSizeClass) private var verticalSizeClass ``` Then you branch in `body`. A recipe browser might show its cards in two columns when the width is compact and in a denser grid when it is regular. Because the property comes from the environment, SwiftUI re-evaluates the view's body when the value changes; you do not subscribe to notifications or cache anything yourself. ## What sets the value Apple's documentation lists the factors SwiftUI uses: - **The device type**: an iPhone and an iPad start from different values. - **The orientation**: rotating an iPhone changes the space available, and the vertical size class typically becomes compact in landscape. - **iPad multitasking**: Slide Over and Split View change the window the app occupies, so an iPad app in a narrow pane typically reports a compact horizontal size class, just like an iPhone. The same documentation tells you to **be prepared for size class changes while the app runs**, because rotation and multitasking happen at runtime. Other platforms are fixed: on watchOS the horizontal size class is always compact, and on macOS and tvOS it is always regular. ## Typical values on iPhone and iPad | Situation | Horizontal | Vertical | |---|---|---| | iPhone, portrait | compact | regular | | iPhone, landscape | compact on most models | compact | | iPad, full screen, either orientation | regular | regular | | iPad, narrow Split View or Slide Over | compact | regular | Read this table as typical rather than guaranteed; some larger iPhones report a regular width in landscape. That uncertainty is exactly why you read the environment instead of hard-coding devices. ## Adapting the layout A common shape is a computed property that turns the size class into one layout decision: 1. Read `horizontalSizeClass` from the environment. 2. Map it to a decision: a column count, a stack axis, whether a secondary panel is visible. 3. Use that decision in `body`, keeping views that hold state outside the branch where you can. Some built-in containers already adapt on their own; a navigation split view, for example, collapses its columns into a single stack at narrow sizes (covered with split navigation). Your own views adapt only when they read the value. ## Common mistakes - **Checking whether the device is an iPad.** The device never changes, but the window does: an iPad app in a narrow Split View pane needs the compact layout. - **Assuming the value is fixed.** Rotation, Split View and Slide Over change it while the app runs. - **Treating the size class as a width.** Two buckets cannot tell you whether four or five grid columns fit. For that, let the grid follow its real width, for example with adaptive `GridItem` columns, or let `ViewThatFits` pick an arrangement that fits. - **Ignoring `nil`.** The property is optional; choose a sensible default, usually the compact layout. - **Forgetting text size.** Size classes say nothing about Dynamic Type. A two-column layout can still need to collapse at accessibility text sizes, which you read from `dynamicTypeSize`. ## Checking your work You can write the value for a subtree with `.environment(\.horizontalSizeClass, .compact)`, which is a quick way to see the compact layout inside a regular window. Before shipping, rotate a real iPad, open the app in Split View and Slide Over, and confirm each layout appears where you expect it.
- What do horizontalSizeClass values look like outside iPhone and iPad?They stop varying. Apple's documentation says that on watchOS the horizontal size class is always `.compact`, and on macOS and tvOS it is always `.regular`. Code shared across platforms therefore still compiles and runs, but the branch you wrote for the other bucket never fires there, so test each platform's real layout rather than relying on the iPad behaviour.
- How can you see a SwiftUI view's compact layout without changing devices?Write the value for a subtree: `.environment(\.horizontalSizeClass, .compact)` on the view makes every descendant read compact, even inside a regular iPad window. It is handy in a preview or a debug screen. It only changes what your views read; it does not change the window, so check the real Split View and Slide Over behaviour on a device too.
- Checking whether the device is an iPad gives the same answer as the size class.
- An iPad app always reports a regular horizontal size class.
- The size class is read once at launch and never changes afterwards.
- horizontalSizeClass tells you the window width in points.
- Rotating an iPhone never changes its vertical size class.