In SwiftUI, how does containerRelativeFrame size a view from its nearest container, for example product gallery cards that show one and a half per screen?
answer
- size from the container, not the parent
- safe area insets subtracted
- count, span and spacing
- iOS 17 and later
basics
~20 sSwiftUI's containerRelativeFrame (iOS 17) sizes a view from its nearest container, such as the screen or a ScrollView, minus that container's safe area insets. Its count, span and spacing form splits that length into columns, so cards can peek.
solid answer
~50 s`containerRelativeFrame(_:alignment:)`, added in iOS 17, gives a view a frame whose size along the chosen axes comes from the **nearest container** rather than from its immediate parent's proposal. Apple lists the containers: the window or, on iOS, the device screen, a `NavigationSplitView` column, a `NavigationStack`, a `TabView` tab, and a scroll view such as `ScrollView` or `List`. The size used is the container's size minus any safe area insets applied to it. The `count:span:spacing:` form divides that length: each column is `(length - spacing * (count - 1)) / count`, and the view takes `span` columns plus the gaps between them, so `count: 3, span: 2` shows one and a half cards. A third form takes a closure `(length, axis) -> CGFloat` for custom maths. For axes you do not pass, the view keeps its own sizing, so pair it with `aspectRatio` for the other dimension.
code
swift · 20 linesimport SwiftUI
struct ProductGallery: View {
let photoNames: [String]
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 12) {
ForEach(photoNames, id: \.self) { name in
RoundedRectangle(cornerRadius: 12)
.fill(Color.gray.opacity(0.2))
.overlay { Text(name) }
.aspectRatio(3.0 / 2.0, contentMode: .fit)
.containerRelativeFrame(.horizontal, count: 3, span: 2, spacing: 12)
}
}
}
.safeAreaPadding(.horizontal, 16)
}
}go deeper
Recall that containerRelativeFrame sizes a view as a fraction of its nearest container, such as the screen or a ScrollView, and that it needs iOS 17.
Explain the count, span and spacing arithmetic, the safe-area subtraction, and why the axes you do not pass keep the view's own sizing.
Replace hand-measured carousels with containerRelativeFrame, keep the spacing argument in sync with the stack, and check rotation and iPad multitasking sizes.
Weigh the iOS 17 deployment floor against the cost of keeping geometry-reader carousels, and decide whether the modifier alone justifies raising the minimum or a fallback path is cheaper.
## The problem it solves Product galleries, onboarding pages and carousels often need items sized as a **fraction of the visible area**: one full-width page, or two-thirds of the width so the next card peeks in. Inside a horizontal `ScrollView`, the immediate parent's proposal is no help, because a scroll view lets its content be as long as it wants. Before iOS 17, teams measured the screen with a geometry reader and passed widths down by hand. `containerRelativeFrame` reads the container's size for you. ## What counts as the container Apple's documentation lists what can represent the **nearest container**: - the window presenting the view on iPadOS or macOS, or the device screen on iOS; - a column of a `NavigationSplitView`; - a `NavigationStack`; - a tab of a `TabView`; - a scrollable view such as `ScrollView` or `List`. The length the modifier works with is that container's size **minus any safe area insets applied to the container**. That detail matters: adding `safeAreaPadding(.horizontal, 20)` to a scroll view shrinks the length its cards are sized from, which is exactly how you give a carousel side margins. ## Three forms | Form | What you control | Typical use | |---|---|---| | `containerRelativeFrame(_ axes:alignment:)` | the axes | full-screen pages | | `containerRelativeFrame(_:count:span:spacing:alignment:)` | a column grid | cards that show a fraction of the next one | | `containerRelativeFrame(_:alignment:_:)` | a closure `(CGFloat, Axis) -> CGFloat` | any custom formula | All three are available from iOS 17, macOS 14, tvOS 17 and watchOS 10. `span` defaults to `1` and `alignment` to `.center`. ## The column formula For the `count:span:spacing:` form, Apple gives the arithmetic: 1. `availableWidth = containerWidth - spacing * (count - 1)` 2. `columnWidth = availableWidth / count` 3. `itemWidth = columnWidth * span + (span - 1) * spacing` Worked example: a 320-point container, `count: 3`, `span: 2`, `spacing: 10`. Available width is 300, each column 100, and the item 2 × 100 + 10 = **210 points**. The first card takes 210 points and the gap 10, so the remaining 100 points show just under half of the next card, giving the "one and a half per screen" look. Pass the same `spacing` to the stack that holds the cards, or the arithmetic and the real gaps disagree and cards drift out of step. ## Only the axes you name The modifier sets a size only along the axes you pass. In the other dimension the view keeps its own sizing, which is why Apple's example uses `.containerRelativeFrame(.horizontal, ...)` together with `aspectRatio(3.0 / 2.0, contentMode: .fit)`: the width comes from the container and the height from the ratio. ## How it fits the proposal model Like `frame(width:height:)`, the modifier wraps the view in an invisible frame. The difference is only where the frame's size comes from: along the axes you pass, it comes from the container instead of from a number you typed. The view inside still takes part in the usual exchange: it is offered that size, chooses its own, and is positioned by the `alignment` parameter. A shape or a resizable image fills the frame; a view with a size of its own, such as a non-resizable image, behaves inside it exactly as it would inside any other frame. ## Compared with the alternatives - **A fixed `frame(width:)`** hard-codes a number that breaks on another device, orientation or iPad multitasking size. - **A geometry reader** works, but it takes all the space offered to it and pushes measurements through your view tree; reading geometry is covered in depth with SwiftUI's geometry tools. - **`containerRelativeFrame`** states the intent declaratively and follows the container's size as layout recomputes. ## Pitfalls - Expecting it to use the immediate parent's size: it skips ordinary parents and looks for the nearest container in the list above. - Forgetting the safe area subtraction and wondering why cards are narrower than the screen. - Mismatching the `spacing` argument and the stack's spacing. - Shipping it to a deployment target below iOS 17, where it is unavailable. Snapping the scroll view to each card is a separate concern, handled by scroll target behaviours in the material on scroll views.
- Why are the cards narrower than expected after adding safeAreaPadding to the ScrollView?`containerRelativeFrame` sizes from the container's size minus any safe area insets applied to it. `safeAreaPadding(.horizontal, 16)` adds 16 points of safe area on each side of the scroll view, so the length the modifier divides is 32 points shorter. That is the intended way to give a carousel side margins.
- When would you use the closure form of containerRelativeFrame?When the column formula does not express the design, for example a width that is a different fraction per axis or that subtracts a fixed amount. The closure receives the container's length and the axis and returns the length to use, so any arithmetic is possible while the size still tracks the container.
- containerRelativeFrame uses the immediate parent's proposed size, like frame.
- The container size includes the safe area insets.
- It is available on every iOS release that supports SwiftUI.
- With count: 3 and span: 2 each item is exactly two-thirds of the screen width.
- Passing .horizontal also fixes the height to the container's height.