skip to content

Flow and Radial Containers

The Layout protocol lets you write a container, such as a flow or radial layout, with the same rules as stacks. Interviewers ask for a tag cloud and when Layout beats nested stacks.

on this pageshow

explore

questions

6

In SwiftUI, why switch a container between HStackLayout and VStackLayout through AnyLayout rather than an if-else choosing HStack or VStack?

level: middleimportance: should knowfreq 45%

answer

  1. same container, new arrangement
  2. structural identity survives
  3. type-erased Layout
  4. children keep their @State

basics

~20 s

AnyLayout type-erases a Layout, so one container keeps its identity while its arrangement changes: children keep their @State and animate to new positions, whereas an if-else between HStack and VStack destroys one subtree and builds another.

solid answer

~40 s

`HStack` and `VStack` are different view types, so an `if-else` between them creates two branches with different structural identity: flipping the condition removes one subtree and inserts the other, the children's `@State` starts over, and any animation plays as a removal and an insertion. `HStackLayout`, `VStackLayout`, `ZStackLayout` and `GridLayout` are the same containers as `Layout` conformers, and `AnyLayout` (iOS 16) erases their type so one expression, `let layout = compact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())`, drives a single container. Apple's docs say it changes the layout type "without destroying the state of the subviews", so with `withAnimation` or `animation(_:value:)` the children move to their new places. It works with custom layouts too, such as collapsing a radial menu into a row.

code

swift · 31 lines
swift
import SwiftUI

struct FilterBar: View {
    @State private var isVertical = false

    var body: some View {
        let layout = isVertical
            ? AnyLayout(VStackLayout(alignment: .leading))
            : AnyLayout(HStackLayout())

        VStack {
            layout {
                FilterChip(title: "Open now")
                FilterChip(title: "Under $20")
                FilterChip(title: "4 stars and up")
            }
            Button("Switch arrangement") {
                withAnimation { isVertical.toggle() }
            }
        }
    }
}

struct FilterChip: View {
    let title: String
    @State private var isOn = false

    var body: some View {
        Toggle(title, isOn: $isOn).toggleStyle(.button)
    }
}

go deeper

for a junior

Remember that HStackLayout and VStackLayout are layout versions of the stacks, and AnyLayout lets one container switch between them.

for a middle

Explain why an if-else gives two identities that reset child state, and how AnyLayout keeps a single container whose arrangement changes.

for a senior

Show you choose the layout value first and call it once, animate with withAnimation or animation(_:value:), and keep child identities stable.

for a principal

Decide where adaptive switches live in shared components, and when switching with AnyLayout suits better than measuring alternatives with ViewThatFits.

## The problem with switching stacks A common adaptive requirement: show a set of controls side by side normally and stack them when space or text size demands it. The obvious code is an `if` that returns an `HStack` in one branch and a `VStack` in the other. It compiles and looks right in a static screenshot, but SwiftUI sees **two different views**. Views in different branches of an `if` have different **structural identity**, and here the containers are different types as well, so when the condition flips SwiftUI removes the old subtree and creates a new one. Two consequences follow: - any `@State` inside the children (a toggle's value, a text field's draft, an expanded section) starts over at its initial value; - an animation, if one is active, plays as the old stack leaving and the new one arriving, not as views sliding to new positions. Wrapping each branch in `AnyView` does not help. Apple's documentation for `AnyView` says that whenever the wrapped view's type changes, "the old hierarchy is destroyed and a new hierarchy is created for the new type." ## What AnyLayout changes `AnyLayout`, added in iOS 16, is a **type-erased `Layout`**. Its initializer, `AnyLayout(_:)`, accepts any value that conforms to the `Layout` protocol, and the result is itself a `Layout`, so you call it like a container: `layout { … }`. Both branches of the choice now produce the same type, so the container and its children keep one identity; only the arrangement algorithm inside changes. Apple's documentation states the purpose directly: `AnyLayout` enables "dynamically changing the type of a layout container without destroying the state of the subviews." The layout value is cheap to build: `HStackLayout()` is a small struct holding an alignment and an optional spacing, so creating it in `body` on every evaluation is the normal pattern, exactly as Apple's own example does with a `let layout = …` line before the container. ## The layout versions of the built-in containers The built-in stacks are views, not layouts, so SwiftUI ships `Layout`-conforming twins for use with `AnyLayout`: | Container view | Layout type | Parameters | |---|---|---| | `HStack` | `HStackLayout` | `alignment:` (vertical), `spacing:` | | `VStack` | `VStackLayout` | `alignment:` (horizontal), `spacing:` | | `ZStack` | `ZStackLayout` | `alignment:` | | `Grid` | `GridLayout` | `alignment:`, `horizontalSpacing:`, `verticalSpacing:` | | your own container | any `Layout` conformer | whatever you define | Apple's guidance on `HStackLayout` is to use plain `HStack` when you don't need a conditional layout; the layout types exist for exactly this switch. Lazy stacks have no layout twin, so they cannot be wrapped. ## Animating the switch Because identity is preserved, an ordinary animation moves each child from its old frame to its new one: 1. Derive the choice from state or an environment value, such as a toggle or `dynamicTypeSize`. 2. Build `AnyLayout(HStackLayout())` or `AnyLayout(VStackLayout())` from that value, in one expression. 3. Change the value inside `withAnimation`, or attach `animation(_:value:)` to the container keyed on the value. Apple's "Composing custom layouts with SwiftUI" sample does this with a custom radial layout: when three pets tie, it swaps `AnyLayout(MyRadialLayout())` for `AnyLayout(HStackLayout())`, and "because the structural identity of the views remains the same throughout, the `animation(_:value:)` view modifier creates animated transitions between layout types." The same technique covers your own containers: because `AnyLayout(_:)` takes any `Layout`, a radial menu can collapse into a row, or a flow of chips can become a single column, with every child animating between the two. ## Pitfalls - **Rebuilding the children per branch.** Calling `VStackLayout() { content }` in one `if` branch and `HStackLayout() { content }` in the other reintroduces the identity break; choose the layout value first, then call it once. - **Reaching for `transition(_:)`.** Transitions animate insertion and removal; nothing is inserted here, so the movement comes from the layout change itself. - **Confusing it with `ViewThatFits`**, which measures alternatives and shows the first one that fits; that tool belongs to grids and adaptive arrangement. - **Using the value-less `animation(_:)`.** It has been deprecated since iOS 15; use `animation(_:value:)` or `withAnimation` instead. - **Unstable child identity inside.** `AnyLayout` preserves the container's identity, not that of children produced by a `ForEach` with unstable IDs.

  • Can AnyLayout switch between a custom layout and a built-in one?
    Yes. `AnyLayout(_:)` accepts any type that conforms to `Layout`, including your own. Apple's custom-layout sample swaps its radial layout for `HStackLayout` when three entries tie, and because the avatars keep their identity, `animation(_:value:)` moves them from the circle into a row.
  • Does AnyLayout protect child state when the children themselves change?
    No, it only preserves identity across the layout switch. Children inside the closure still follow the normal identity rules: a `ForEach` keyed on stable IDs keeps each child's state, while children keyed on unstable values, or placed in their own `if` branches, can still reset.

Rearranging the furniture in one room rather than moving into a different room: the chairs are the same chairs, the coat stays on the back of one, and you can watch them slide into their new places.

  • An if-else between HStack and VStack keeps child @State because the child code is identical.
  • Wrapping each branch in AnyView preserves state across the switch.
  • AnyLayout can wrap a LazyVStack for long content.
  • Switching layouts needs matchedGeometryEffect on every child to animate.
  • AnyLayout requires iOS 17 or later.
open as a page

In SwiftUI's Layout protocol, what do sizeThatFits and placeSubviews each do, and how does a layout reach its subviews?

level: middleimportance: should knowfreq 40%

basics

~10 s

A 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.

open as a page

How would you build a wrapping row of filter chips with SwiftUI's Layout protocol, and how should sizeThatFits treat the proposed width?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Measure each chip's ideal size, start a new row whenever the next chip would pass the proposed width, and return the widest row and total height; placeSubviews repeats that row-breaking against bounds.width so placement matches the reported size.

open as a page

For a team's shared SwiftUI component library, when would you standardise on a custom Layout instead of nested stacks or GeometryReader?

level: principalimportance: should knowfreq 25%

basics

~20 s

Adopt a custom Layout when an arrangement must measure siblings against offered space, like wrapping chips or equal-width buttons; keep stacks for what they express, and keep GeometryReader out of sizing, since it takes flexible space.

open as a page

In a radial quick-action menu built with SwiftUI's Layout protocol, how do you give the layout per-button data such as a fixed angle?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

Declare a LayoutValueKey with a defaultValue, set it on each button with layoutValue(key:value:), usually wrapped in a View extension, and read it inside the layout with subview[Key.self]; buttons that never set it read the default.

open as a page

In a custom SwiftUI Layout, when do makeCache and updateCache run, and what is safe to keep in the layout cache?

level: seniorimportance: nice to knowfreq 20%

basics

~10 s

makeCache(subviews:) builds storage that a layout's methods receive inout; SwiftUI calls updateCache(_:subviews:) when the subviews change, and its default rebuilds through makeCache. Keep subview-derived measurements there and key anything that depends on the proposal.

open as a page