skip to content

In SwiftUI, how would you build a tab indicator that slides to match the width and position of the selected tab label?

level: seniorimportance: nice to knowfreq 25%

answer

  1. geometry as an opaque value
  2. the selected label publishes its bounds
  3. the container resolves it
  4. proxy subscript in an overlay

basics

~20 s

Have the selected label publish its bounds with anchorPreference(key:value:transform:) as an Anchor<CGRect>, then in the tab row's overlayPreferenceValue add a GeometryReader that resolves it with proxy[anchor] and draws the indicator there, animated on the selection.

solid answer

~40 s

Use an anchor preference. Each tab label attaches `.anchorPreference(key: SelectedTabKey.self, value: .bounds) { tab == selection ? $0 : nil }`, so only the selected label publishes an `Anchor<CGRect>`; the key's `reduce` keeps the non-nil one with `value = value ?? nextValue()`. On the tab row, `.overlayPreferenceValue(SelectedTabKey.self) { anchor in GeometryReader { proxy in ... } }` receives that anchor, and `proxy[anchor]` converts it to a `CGRect` in the overlay's own coordinate space. Draw a `Capsule` with that width at that x offset, and add `.animation(.snappy, value: selection)` so it slides. An anchor is opaque geometry that its reader resolves into its own space, so you need no named coordinate space and no `@State` holding frames.

code

swift · 34 lines
swift
struct SelectedTabKey: PreferenceKey {
    static let defaultValue: Anchor<CGRect>? = nil
    static func reduce(value: inout Anchor<CGRect>?, nextValue: () -> Anchor<CGRect>?) {
        value = value ?? nextValue()
    }
}

struct CategoryTabs: View {
    let tabs = ["All", "Electronics", "Home", "Garden"]
    @State private var selection = "All"

    var body: some View {
        HStack(spacing: 20) {
            ForEach(tabs, id: \.self) { tab in
                Button(tab) { selection = tab }
                    .anchorPreference(key: SelectedTabKey.self, value: .bounds) { anchor in
                        tab == selection ? anchor : nil
                    }
            }
        }
        .overlayPreferenceValue(SelectedTabKey.self) { anchor in
            GeometryReader { proxy in
                if let anchor {
                    let rect = proxy[anchor]
                    Capsule()
                        .frame(width: rect.width, height: 3)
                        .offset(x: rect.minX, y: rect.maxY + 4)
                        .allowsHitTesting(false)
                }
            }
        }
        .animation(.snappy, value: selection)
    }
}

go deeper

for a junior

Recall that a child can publish its geometry upward with anchorPreference and a parent can draw from it with overlayPreferenceValue.

for a middle

Explain the parts: an Anchor<CGRect> from the .bounds source, a key whose reduce keeps the non-nil anchor, and a GeometryReader in the overlay that resolves it with proxy[anchor].

for a senior

Defend the design: anchors avoid named spaces and frame state, reduce must not overwrite, the overlay must not block taps, and animation(_:value:) keyed to the selection makes it slide. Know when matchedGeometryEffect is simpler.

for a principal

For a shared tab component, the choice is between anchor preferences and matchedGeometryEffect; pick the one the team can extend, such as indicators spanning tabs, and keep it inside the component.

## The scenario A horizontal tab bar shows category labels of different widths, such as "All", "Electronics" and "Home". Under the selected label there is an indicator, a thin capsule that must be **exactly as wide as the selected label** and **slide** to the next one when the selection changes. The labels' widths depend on the strings, the font and Dynamic Type, so hard-coding them is not an option. The container needs the selected child's frame. ## Why an anchor rather than a CGRect You could measure each label with a `GeometryReader` in its background, convert its frame into a named coordinate space on the tab row, and send that `CGRect` up through a preference. It works, but every child must know which space to convert into. An **anchor** removes that coupling. - **`Anchor<Value>`** is, in Apple's words, an opaque value derived from an anchor source and a particular view. You convert it to a `Value` in the coordinate space of a target view by using that view's `GeometryProxy`. - **`anchorPreference(key:value:transform:)`** sets a preference whose value is a function of a geometry value tied to the current coordinate space, allowing readers of the value to convert the geometry to their local coordinates. - **`Anchor<CGRect>.Source.bounds`** is the source for a view's whole bounds; `.rect(_:)` gives a sub-rectangle. So the child says "here are my bounds", and the reader decides which space to see them in. ## Building it step by step 1. **Define the key.** `Value` is `Anchor<CGRect>?`, `defaultValue` is `nil`, and `reduce` keeps the first non-nil value: `value = value ?? nextValue()`. Only one tab publishes a non-nil anchor, so that one wins wherever it sits in the row. 2. **Publish from the selected tab.** On each label, `.anchorPreference(key: SelectedTabKey.self, value: .bounds) { anchor in tab == selection ? anchor : nil }`. 3. **Resolve in the container.** On the `HStack`, `.overlayPreferenceValue(SelectedTabKey.self) { anchor in ... }`. The closure receives the combined value and returns a view drawn over the row. 4. **Get a proxy.** Inside the overlay, a `GeometryReader` is proposed the row's size, so it covers the row exactly and changes nothing about the layout. `proxy[anchor]` returns the selected label's rectangle in the reader's coordinates. 5. **Draw and animate.** A `Capsule` with `.frame(width: rect.width, height: 3)` and `.offset(x: rect.minX, y: rect.maxY + 4)`; then `.animation(.snappy, value: selection)` on the row so the width and offset interpolate when the selection changes. Because the anchor comes from the label's current layout, the indicator follows Dynamic Type changes, localized strings of different lengths and rotation without any extra code. ## Comparing the options | Approach | Coordinate space set-up | State holding frames | Fits | |---|---|---|---| | Anchor preference + `overlayPreferenceValue` | none: the reader resolves | none | indicators, connectors, callouts from children's frames | | `CGRect` preference in a named space | each child converts | optional | when the value must also be stored or logged | | `onGeometryChange` per tab into a dictionary | each child converts | yes | when other logic needs every tab's frame | | `matchedGeometryEffect` | none | none | moving one view between places | `matchedGeometryEffect`, covered with hero animations, can also produce a sliding underline by placing the capsule inside the selected tab with a shared id. It moves a view rather than reading geometry. Anchor preferences win when the container must **compute** from children's frames, for example an indicator spanning two tabs, or a line connecting a label to a detail panel. ## Pitfalls - **`reduce` that overwrites.** With `value = nextValue()` the result is whatever the last tab published, usually `nil`, and the indicator vanishes unless the last tab is selected. - **Resolving with the wrong proxy.** `proxy.frame(in: .local)` is the reader's own frame, not the anchor's; only the subscript `proxy[anchor]` converts the anchor. - **Storing anchors in state to resolve later.** An anchor is meant to be resolved by a proxy where the preference is read; `overlayPreferenceValue` and `backgroundPreferenceValue` exist so you can do that without state. - **Forgetting the animation value.** Without `animation(_:value:)` keyed to the selection, the capsule jumps instead of sliding. - **Hit testing.** The overlay sits above the buttons; add `.allowsHitTesting(false)` to the capsule if it overlaps the labels.

  • How does matchedGeometryEffect compare for the same indicator?
    `matchedGeometryEffect`, covered with hero animations, can slide one capsule between tabs by giving it the same id inside whichever tab is selected. It moves a view between places rather than reading geometry, so it suits a plain underline. Anchor preferences fit when the container must compute from children's frames, such as an indicator spanning two tabs.
  • Why put a GeometryReader inside overlayPreferenceValue?
    `overlayPreferenceValue` hands you the combined preference value but no geometry. Resolving an anchor needs a `GeometryProxy` for the target space, and a reader inside the overlay is proposed the row's size, so it covers the row exactly without disturbing the layout. Its subscript then turns the anchor into a rectangle in the row's coordinates.

  • An Anchor is already a CGRect in global coordinates
  • reduce can assign value = nextValue() since one tab sets it
  • Each tab must convert its frame into a named coordinate space
  • proxy.frame(in: .local) gives the selected tab's rectangle
  • Anchors should be stored in @State and resolved later