In SwiftUI's Layout protocol, what do sizeThatFits and placeSubviews each do, and how does a layout reach its subviews?
answer
- two required methods
- report a size, then position
- proxies, not the views
- place once per subview
basics
~10 sA SwiftUI Layout implements sizeThatFits(proposal:subviews:cache:) to report the container's size for a proposal, and placeSubviews(in:proposal:subviews:cache:) to position each child by calling place(at:anchor:proposal:) on its LayoutSubview proxy.
solid answer
~30 sThe `Layout` protocol, added in iOS 16, has two required methods. `sizeThatFits(proposal:subviews:cache:)` receives the parent's `ProposedViewSize` and returns the `CGSize` the container wants; to compute it you measure children through their proxies with `subview.sizeThatFits(_:)`. `placeSubviews(in:proposal:subviews:cache:)` receives the bounds the container was actually given and calls `place(at:anchor:proposal:)` on each `LayoutSubview`, once per subview as Apple's docs say. You never touch the child views themselves: `subviews` is a `LayoutSubviews` collection of proxies exposing sizes, `ViewSpacing` preferences, layout priority and custom layout values. You then use the type like a stack, `MyLayout { … }`.
code
swift · 27 linesimport SwiftUI
struct EqualWidthHStack: Layout {
var spacing: CGFloat = 8
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
guard !subviews.isEmpty else { return .zero }
let widest = maxSize(of: subviews)
let gaps = spacing * CGFloat(subviews.count - 1)
return CGSize(width: widest.width * CGFloat(subviews.count) + gaps, height: widest.height)
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let widest = maxSize(of: subviews)
var x = bounds.minX
for subview in subviews {
subview.place(at: CGPoint(x: x, y: bounds.midY), anchor: .leading, proposal: ProposedViewSize(widest))
x += widest.width + spacing
}
}
private func maxSize(of subviews: Subviews) -> CGSize {
subviews.map { $0.sizeThatFits(.unspecified) }.reduce(.zero) {
CGSize(width: max($0.width, $1.width), height: max($0.height, $1.height))
}
}
}go deeper
Recall that a custom container conforms to Layout and implements two methods: one returns the container's size, the other places each child.
Explain the proxies: measure with sizeThatFits(_:) on a LayoutSubview, then call place(at:anchor:proposal:) once per child inside placeSubviews, offset from the bounds origin.
Show you keep measuring and placing consistent, handle nil proposal dimensions on purpose, and expect a parent to ask for a size several times.
Frame Layout as the escape hatch after the built-in containers, and weigh its review and maintenance cost against how often the team needs it.
## What a custom Layout is SwiftUI's built-in containers (`HStack`, `VStack`, `ZStack`, `Grid`) cover most screens. For arrangements they cannot express, iOS 16 added the **`Layout` protocol**: a type that conforms to it becomes a container you use exactly like a stack, by calling it with a view-builder closure (`MyLayout { … }`). Apple's documentation sums up the job: a container you define "asks for the sizes of all its subviews, and then indicates where to place the subviews within its own bounds." A `Layout` is a plain struct of parameters such as spacing, radius or alignment. It is not a `View` and has no `body`; SwiftUI calls its methods while it lays out the screen. ## The two required methods Only two requirements have no default implementation: 1. **`sizeThatFits(proposal:subviews:cache:)`** receives a `ProposedViewSize` from the container's parent and returns the `CGSize` the container wants. Each dimension of the proposal is an optional `CGFloat`; `nil` means the parent is asking for the container's ideal size in that dimension. To answer, the layout usually measures its children first. 2. **`placeSubviews(in:proposal:subviews:cache:)`** receives `bounds`, the rectangle the container was actually given, and tells each child where to go by calling **`place(at:anchor:proposal:)`** on it. Apple's `LayoutSubview` documentation says to do this once for each subview. The order matters for reasoning. Parents commonly probe a child with several proposals before deciding, so your `sizeThatFits` can be asked more than once; `placeSubviews` then works inside the final bounds. A layout that measures one way and places another puts children outside the size it reported. ## Subviews are proxies, not views The `subviews` parameter is a `LayoutSubviews` collection (the protocol aliases it as `Subviews`) with exactly one **`LayoutSubview`** proxy per child. A layout "can't interact directly with its subviews", in Apple's words; the proxy is the whole interface: - `sizeThatFits(_:)` asks the child how big it would be for a proposal you choose, for example `.unspecified` for its ideal size. - `dimensions(in:)` returns `ViewDimensions`, which adds alignment-guide values to the size. - `spacing` returns the child's `ViewSpacing` preferences, so you can honour platform spacing between neighbours. - `priority` exposes the value set with `layoutPriority(_:)`. - A subscript, `subview[SomeKey.self]`, reads a custom value set with `layoutValue(key:value:)`. - `place(at:anchor:proposal:)` commits a position. The anchor defaults to `.topLeading`, and the proposal you pass is the size offer the child lays itself out against. Because the proxy can only measure and place, a layout cannot add padding, change a colour or reorder a child's modifiers; that stays in the view code that builds the children. ## Optional requirements | Requirement | When you omit it | Use it to | |---|---|---| | `makeCache(subviews:)` | a default exists only when `Cache` is `Void` | share measurements between methods | | `updateCache(_:subviews:)` | the default calls `makeCache(subviews:)` again | refresh the cache when subviews change | | `spacing(subviews:cache:)` | a default implementation | report the container's own spacing preferences | | `explicitAlignment(of:in:proposal:subviews:cache:)` | a default implementation | expose alignment guides for the container | | `layoutProperties` | a default `LayoutProperties` value | declare a `stackOrientation` | ## A worked example and the classic mistakes Apple's "Composing custom layouts with SwiftUI" sample builds an equal-width button row. `sizeThatFits` measures every button's ideal size, takes the largest, and returns that width times the button count plus the spacing. `placeSubviews` walks from `bounds.minX`, placing each button in its slot with a proposal of that common size, so every button stretches to match the widest one. The mistakes interviewers listen for: - **Ignoring the origin of `bounds`.** Apple's samples compute every position from `bounds.minX`, `bounds.midX` and `bounds.midY`; doing the same keeps the layout correct wherever its parent puts it. - **Placing with a different proposal than you measured with.** The child sizes itself to the proposal passed to `place`, so the arrangement drifts from the size you reported. - **Treating `nil` as zero.** An unspecified dimension asks for the ideal size; `replacingUnspecifiedDimensions(by:)` turns it into a concrete value, with a 10 by 10 point fallback when you pass no argument. - **Wrapping children in `GeometryReader`** to learn their sizes, when the proxies already measure them.
- Why compute positions from bounds.minX and bounds.minY instead of from zero?The bounds rectangle is the region the parent granted, and nothing promises its origin is zero. Apple's own layout samples always offset from `bounds.minX`, `bounds.midX` and `bounds.midY`, and copying that keeps the container correct wherever its parent places it.
- Why might your sizeThatFits be called more than once during layout?Parents commonly measure a child with several proposals before deciding; Apple's `ProposedViewSize` docs list zero, infinity and unspecified as typical probes. So `sizeThatFits` must answer each proposal consistently from its inputs alone, never by remembering the last call, and that repetition is one reason the protocol offers a cache.
- A custom Layout can add padding or other modifiers to its children.
- sizeThatFits runs exactly once, right before placeSubviews.
- Positions in placeSubviews can ignore bounds.minX and bounds.minY.
- The Layout protocol needs iOS 17 because it shipped with Observation.
- A layout needs GeometryReader to learn how big each child is.