skip to content

In SwiftUI, how do you use a PreferenceKey to report each child's height to a parent, and what must reduce(value:nextValue:) do?

level: seniorimportance: should knowfreq 42%

answer

  1. the opposite direction to the environment
  2. many children, one combined value
  3. defaultValue and reduce
  4. measure before you apply

basics

~20 s

Define a PreferenceKey, have each child set its measured height with preference(key:value:), and read the combined result in the parent with onPreferenceChange(_:perform:). reduce(value:nextValue:) must merge each next value into the running one, for example with max, or only one child's value survives.

solid answer

~40 s

A preference sends a value from children up to ancestors, the reverse of the environment. You declare a type conforming to `PreferenceKey` with a `defaultValue` and a `static func reduce(value:nextValue:)`. Each child measures itself, typically with a `GeometryReader` in its `.background`, and attaches `.preference(key: MaxHeightKey.self, value: proxy.size.height)`. SwiftUI combines the values from all children through `reduce`, so for "tallest card" `reduce` must do `value = max(value, nextValue())`; assigning `nextValue()` keeps only one child's height. The parent reads the result with `.onPreferenceChange(MaxHeightKey.self) { cardHeight = $0 }`, which requires the value to be `Equatable` and runs when the combined value changes. Then apply the stored height as a frame, but measure before that frame, or the children report their own adjusted size and the value can keep growing.

code

swift · 30 lines
swift
struct MaxHeightKey: PreferenceKey {
    static let defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = max(value, nextValue())
    }
}

struct PlanPicker: View {
    let plans: [String]
    @State private var cardHeight: CGFloat?

    var body: some View {
        HStack(alignment: .top, spacing: 12) {
            ForEach(plans, id: \.self) { plan in
                Text(plan)
                    .padding()
                    .background {
                        GeometryReader { proxy in
                            Color.clear
                                .preference(key: MaxHeightKey.self, value: proxy.size.height)
                        }
                    }
                    .frame(height: cardHeight, alignment: .top)
                    .frame(maxWidth: .infinity)
                    .background(.quaternary, in: .rect(cornerRadius: 12))
            }
        }
        .onPreferenceChange(MaxHeightKey.self) { cardHeight = $0 }
    }
}

go deeper

for a junior

Recall that preferences send values up to ancestors, the opposite of the environment, and that a PreferenceKey needs a defaultValue and a reduce function.

for a middle

Walk through the pipeline: measure in a background reader, set preference(key:value:), combine through reduce, read with onPreferenceChange, then apply the height.

for a senior

Show production judgment: a reduce that merges rather than overwrites, a neutral default, measuring before the frame that uses the result to avoid a growing value, and knowing when onGeometryChange or a layout tool is simpler.

for a principal

The angle is reuse: a shared PreferenceKey lets components report measurements without knowing their parent, which keeps a component library decoupled; weigh that against a custom Layout that needs no measuring.

## Preferences: values that flow up SwiftUI has two channels for configuration. The **environment** flows **down**: a container sets a value and every descendant can read it. **Preferences** flow **up**: a subview sets a value and its ancestors can read it. Apple's documentation describes the difference: a single container must reconcile potentially conflicting preferences flowing up from many subviews, so when you define a preference you also say **how to merge** values from multiple subviews. Built-in modifiers use the same machinery; the documentation names `navigationTitle(_:)` as one that relies on preferences to send configuration up to its container. ## The PreferenceKey protocol A preference is identified by a type that conforms to **`PreferenceKey`**. It has two requirements: - **`defaultValue`**: the value the key has when no view in the subtree sets it. Choose a value that means "nothing measured" and that `reduce` would leave unchanged: `0` for a maximum of non-negative heights, an empty array for a collection, `nil` for an optional. - **`reduce(value:nextValue:)`**: merges one more value into the accumulated one. `value` is `inout`; `nextValue` is a closure that returns the next child's value. Common `reduce` bodies: | Goal | `reduce` body | |---|---| | Tallest child | `value = max(value, nextValue())` | | All children's heights | `value.append(contentsOf: nextValue())` | | Heights keyed by id | `value.merge(nextValue()) { $1 }` | | The one child that sets it | `value = value ?? nextValue()` | The classic mistake is `value = nextValue()`, which overwrites instead of merging, so the parent sees whichever child happened to be combined last. In the Swift 6 language mode, declare `defaultValue` as a `static let` (or a computed property): the compiler reports a `static var` with an initial value as unsafe global mutable state. ## Wiring it end to end 1. **Measure each child.** Attach `.background { GeometryReader { proxy in Color.clear.preference(key: MaxHeightKey.self, value: proxy.size.height) } }`. The reader in the background is proposed the child's size, so it measures without changing the layout. 2. **Combine.** SwiftUI calls `reduce` as it gathers the values of the children under a common ancestor. 3. **Read in the parent.** `.onPreferenceChange(MaxHeightKey.self) { cardHeight = $0 }` runs when the combined value changes. The value type must be `Equatable` for this modifier. 4. **Apply.** Give each child `.frame(height: cardHeight, alignment: .top)` so all cards share the tallest height. A view in the middle of the tree can adjust a value on its way up with `transformPreference(_:_:)`, for example adding its own padding to a child's reported height, without the children knowing anything about it. If the parent only needs the value to **draw** something, `overlayPreferenceValue(_:_:)` and `backgroundPreferenceValue(_:_:)` build a view straight from it without any `@State`. ## What goes wrong in production - **Overwriting in `reduce`.** Only one child's value survives; cards line up with a random card instead of the tallest. - **A misleading `defaultValue`.** A default such as `44` makes "nothing measured yet" look like a real height; prefer `0` or `nil` so the parent can tell the cases apart. - **Measuring after applying.** If the background reader sits after the `.frame(height:)` and after extra padding, each pass measures the adjusted size, reports something larger, and the stored maximum keeps growing. Measure the child's natural size **before** the frame and padding that use the result. - **Expecting siblings to see it.** Preferences reach ancestors. A sibling can only use the value if a common ancestor reads it and passes it back down, for example as a parameter or through the environment. - **Doing heavy work in the handler.** The handler writes state, which updates the views that read it; keep it to an assignment. ## When a preference is the right tool Use a preference when **many children, possibly deep inside reusable components, contribute to one value the parent owns**. Each child only declares its measurement; it needs no binding or callback into the parent. When a single view needs its own size, `onGeometryChange(for:of:action:)` on that view is simpler. When the aim is pure layout, such as equal widths in a row, check first whether a stack, a `Grid` or a custom `Layout` can express it without measuring at all.

  • When is a PreferenceKey better than onGeometryChange writing into the parent's state?
    When many children, possibly inside reusable components, contribute to one value the parent owns. Each child only declares its measurement and SwiftUI combines them through `reduce`, so the children need no binding or callback into the parent. With `onGeometryChange` every child would need that callback and the parent would merge values by hand.
  • How can a parent use a preference value without storing it in @State?
    With `overlayPreferenceValue(_:_:)` or `backgroundPreferenceValue(_:_:)`. Each reads the combined preference from the view it's attached to and builds an overlay or background view from it directly. That suits drawing something from children's values, such as a highlight or a connector line, and avoids a state write and the extra update it causes.
  • What value should a PreferenceKey's defaultValue hold?
    It is the value the key has when no view in the subtree sets it, so it should mean "nothing measured" and be a value `reduce` would leave unchanged: 0 for a maximum of heights, an empty array or dictionary for collections, nil for an optional. A plausible-looking default such as 44 hides the case where no child reported anything.

  • reduce can simply assign value = nextValue()
  • Preferences flow down from a parent to its children
  • A sibling view can read another sibling's preference directly
  • onPreferenceChange works with any value type, Equatable or not
  • The measuring reader can go after the frame that uses the result