Pocket How
SwiftUI

SwiftUI Layout protocol: build a flow layout with caching and layout values

iOS 16+, iPadOS 16+. Advanced. By Cihat Salik, .

Short answer

Conform a struct to Layout, measure subviews in sizeThatFits(proposal:subviews:cache:) for every kind of proposal, and position them in placeSubviews(in:proposal:subviews:cache:) relative to bounds.minX and bounds.minY. Add a cache only when profiling shows repeated measurement is costly, pass per-view options with LayoutValueKey, and switch layouts with AnyLayout to keep view identity.

The problem

Some arrangements don’t fit stacks and grids. Tags that wrap onto the next line, a radial menu, a row where one item takes whatever space is left after the others. Before iOS 16 you faked these with GeometryReader, preference keys and a second layout pass, and the result jittered on first render. The Layout protocol (iOS 16+) lets you write the layout algorithm directly, in the same two-phase negotiation SwiftUI uses for its own stacks.

How layout negotiation works

SwiftUI lays out views top-down in two steps. A parent proposes a size to each child. The child answers with the size it wants. The parent then places each child at a position of its choosing. A custom layout does both halves for its own subviews:

  • sizeThatFits(proposal:subviews:cache:) receives the proposal from your parent and returns the size your container wants.
  • placeSubviews(in:proposal:subviews:cache:) receives the final bounds and calls place(at:anchor:proposal:) on each subview.

You never touch the subviews themselves. Each method gets a Subviews collection of LayoutSubview proxies, which you can ask for a size under a given proposal, for spacing preferences, for priority and for custom layout values.

What a proposal means

ProposedViewSize has an optional width and height, and each dimension carries a different question. Javier Nigro lays these out in The SwiftUI Layout Protocol – Part 1:

Proposed dimension It asks for
nil The ideal size
0 The minimum size
.infinity The maximum size
A finite value The size the view wants within that space

ProposedViewSize.unspecified is nil in both dimensions. Javier also stresses that SwiftUI calls sizeThatFits several times with different proposals to learn how flexible your container is. Your implementation has to give a sensible answer to every one of them, including nil and .infinity, and has to be cheap enough to run repeatedly.

A flow layout, step by step

A flow layout behaves like an HStack until a row is full, then wraps to the next line. Majid Jabrayilov builds a minimal version in Building custom layout in SwiftUI. Basics., measuring ideal sizes and starting a new line when the proposed width runs out. The version below adds what a production layout needs: system spacing, oversize items, alignment within a row, a forced line break and an optional cache.

Step 1: a shared arrangement function

Both protocol methods need the same answer to “which subview goes on which row, at what offset.” Computing it in one function keeps the two passes consistent.

import SwiftUI

struct FlowLayout: Layout {
    var spacing: CGFloat?
    var lineSpacing: CGFloat = 8
    var alignment: VerticalAlignment = .center

    struct Row {
        var indices: [Int] = []
        var xOffsets: [CGFloat] = []
        var width: CGFloat = 0
        var height: CGFloat = 0
    }

    private func arrange(
        maxWidth: CGFloat,
        subviews: Subviews,
        sizes: [CGSize]
    ) -> [Row] {
        var rows: [Row] = []
        var current = Row()

        for index in subviews.indices {
            let size = sizes[index]
            let gap = current.indices.last.map { gapBetween($0, index, subviews) } ?? 0
            let forcesBreak = subviews[index][StartsNewLine.self]
            let overflows = current.width + gap + size.width > maxWidth

            if !current.indices.isEmpty && (forcesBreak || overflows) {
                rows.append(current)
                current = Row()
            }

            let x = current.indices.isEmpty ? 0 : current.width + gap
            current.indices.append(index)
            current.xOffsets.append(x)
            current.width = x + size.width
            current.height = max(current.height, size.height)
        }

        if !current.indices.isEmpty { rows.append(current) }
        return rows
    }

    private func gapBetween(_ leading: Int, _ trailing: Int, _ subviews: Subviews) -> CGFloat {
        if let spacing { return spacing }
        return subviews[leading].spacing.distance(to: subviews[trailing].spacing, along: .horizontal)
    }
}

When spacing is nil, the gap comes from each subview’s ViewSpacing preferences, the same way an HStack picks system spacing between a Text and an Image. Javier’s article covers how spacing.distance(to:along:) reads those preferences.

Step 2: measure and handle oversize items

A tag wider than the container should wrap its own text instead of overflowing. Measure the ideal size first, and when it exceeds the available width, ask again with that width as a constraint.

extension FlowLayout {
    func measure(_ subviews: Subviews, maxWidth: CGFloat) -> [CGSize] {
        subviews.map { subview in
            let ideal = subview.sizeThatFits(.unspecified)
            guard ideal.width > maxWidth else { return ideal }
            return subview.sizeThatFits(ProposedViewSize(width: maxWidth, height: nil))
        }
    }
}

Step 3: sizeThatFits

extension FlowLayout {
    func sizeThatFits(
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout Cache
    ) -> CGSize {
        let maxWidth = proposal.width ?? .infinity
        let sizes = cache.sizes(for: subviews, maxWidth: maxWidth, layout: self)
        let rows = arrange(maxWidth: maxWidth, subviews: subviews, sizes: sizes)

        let width = rows.map(\.width).max() ?? 0
        let height = rows.map(\.height).reduce(0, +)
            + lineSpacing * CGFloat(max(rows.count - 1, 0))
        return CGSize(width: width, height: height)
    }
}

A nil or infinite width puts everything on one row, which is the right ideal size for a flow layout. The container reports the width it actually uses, never the proposed width. Returning proposal.width would claim infinite width when asked for a maximum.

Step 4: placeSubviews

extension FlowLayout {
    func placeSubviews(
        in bounds: CGRect,
        proposal: ProposedViewSize,
        subviews: Subviews,
        cache: inout Cache
    ) {
        let sizes = cache.sizes(for: subviews, maxWidth: bounds.width, layout: self)
        let rows = arrange(maxWidth: bounds.width, subviews: subviews, sizes: sizes)
        var y = bounds.minY

        for row in rows {
            for (position, index) in row.indices.enumerated() {
                let size = sizes[index]
                let yOffset: CGFloat = switch alignment {
                case .top: 0
                case .bottom: row.height - size.height
                default: (row.height - size.height) / 2
                }
                subviews[index].place(
                    at: CGPoint(x: bounds.minX + row.xOffsets[position], y: y + yOffset),
                    anchor: .topLeading,
                    proposal: ProposedViewSize(size)
                )
            }
            y += row.height + lineSpacing
        }
    }
}

Offsets start at bounds.minX and bounds.minY. Javier warns that the origin is usually zero but not always, because a parent can place your container anywhere. Code that assumes (0, 0) works in a preview and breaks inside another layout.

Pass each subview the size you measured as its proposal. Proposing .unspecified here would let a wrapped text view snap back to one long line.

Step 5: the cache

The Cache associated type defaults to Void. When you declare your own, implement makeCache(subviews:). Majid’s caching article explains the lifecycle, and Apple’s updateCache(_:subviews:) documentation confirms the default: when the layout or its subviews change, SwiftUI calls updateCache, and the default implementation simply calls makeCache again.

extension FlowLayout {
    struct Cache {
        var maxWidth: CGFloat = -1
        var measured: [CGSize] = []

        mutating func sizes(for subviews: Subviews, maxWidth: CGFloat, layout: FlowLayout) -> [CGSize] {
            if maxWidth != self.maxWidth || measured.count != subviews.count {
                measured = layout.measure(subviews, maxWidth: maxWidth)
                self.maxWidth = maxWidth
            }
            return measured
        }
    }

    func makeCache(subviews: Subviews) -> Cache {
        Cache()
    }
}

The cache stores measurements per width. A repeated proposal with the same width reuses them, a new width measures again, and any change to the subviews resets the cache through the default updateCache.

Do you need this at all? Javier logged the calls in his tests and found the cache built twice while the other methods ran 25 times, and both he and Majid treat caching as something to add when performance requires it. That matches my recommendation: write the layout without a cache, profile it with your real content, and add one when measurement shows up in the trace. A wrong cache gives you stale sizes, which is a worse bug than a slow layout.

Step 6: per-view options with LayoutValueKey

Sometimes one subview needs to tell the container something. A LayoutValueKey declares a value with a default, a view sets it with layoutValue(key:value:), and the container reads it by subscripting the proxy. Here it forces a line break, which arrange already checks:

private struct StartsNewLine: LayoutValueKey {
    static let defaultValue = false
}

extension View {
    func startsNewLine(_ value: Bool = true) -> some View {
        layoutValue(key: StartsNewLine.self, value: value)
    }
}

The same mechanism carries weights, priorities or a preferred row. The built-in layoutPriority(_:) reaches your layout through the proxy’s priority property.

Using it

struct TagCloud: View {
    let tags: [String]

    var body: some View {
        FlowLayout(lineSpacing: 6, alignment: .center) {
            Text("Topics").font(.headline).startsNewLine()
            ForEach(tags, id: \.self) { tag in
                Text(tag)
                    .padding(.horizontal, 10)
                    .padding(.vertical, 6)
                    .background(.quaternary, in: Capsule())
            }
        }
        .padding()
    }
}

Because the layout has default values for every property, you can also write FlowLayout() with empty parentheses. Apple’s Layout documentation explains the quirk: without parentheses, the callAsFunction call site looks for an initializer with zero arguments, so a layout with defaults needs either () or an explicit init().

AnyLayout: change the layout, keep identity

Swapping HStack for VStack in an if/else creates two different views. Their state resets and the change plays as a removal and insertion. AnyLayout (iOS 16+) type-erases a layout so both branches are the same view with a different algorithm. Apple’s documentation shows the classic use: switch from horizontal to vertical at accessibility text sizes.

struct ProfileHeader: View {
    @Environment(\.dynamicTypeSize) private var dynamicTypeSize

    var body: some View {
        let layout = dynamicTypeSize.isAccessibilitySize
            ? AnyLayout(VStackLayout(alignment: .leading, spacing: 12))
            : AnyLayout(HStackLayout(spacing: 16))

        layout {
            Image(systemName: "person.crop.circle.fill")
                .font(.largeTitle)
                .accessibilityHidden(true)
            VStack(alignment: .leading) {
                Text("Ada Lovelace").font(.title2.bold())
                Text("Analyst").foregroundStyle(.secondary)
            }
        }
    }
}

Use HStackLayout, VStackLayout, ZStackLayout and GridLayout here. They are the Layout-conforming versions of the familiar containers. Your own FlowLayout fits the same slot. Javier points out that since identity is preserved, wrapping the change in withAnimation animates every subview to its new position with no extra code.

If you only need to pick whichever of several fixed layouts fits the space, ViewThatFits (iOS 16+) is simpler. Use AnyLayout when the choice depends on state rather than on available size.

Other hooks worth knowing

  • spacing(subviews:cache:) tells the views around your container how much space it prefers. Without it, the container reports default spacing.
  • explicitAlignment(of:in:proposal:subviews:cache:) lets your container define where alignment guides such as .firstTextBaseline fall, so it lines up correctly inside an outer HStack.
  • layoutProperties declares a stack orientation for containers that behave like a stack.
  • Layout conforms to Animatable and Sendable. Stored properties that you expose through animatableData animate when they change, which is how you animate a radial layout’s angle. In Swift 6, keep the layout’s properties Sendable value types.

Traps

  • Assuming one call. sizeThatFits runs for several proposals, and results from one call aren’t automatically valid for the next unless your cache checks the inputs.
  • Placing outside the bounds origin. Always offset from bounds.minX and bounds.minY.
  • Sizing and placement disagreeing. Apple’s placeSubviews documentation asks for computations that match sizeThatFits for the same inputs. Spacing added in one pass and forgotten in the other makes the container report a size its content doesn’t fill. The shared arrange function exists to prevent exactly that.
  • Measuring with GeometryReader inside subviews. Reading a size and writing it to state causes a second layout pass. The WWDC26 session Dive into lazy stacks and scrolling shows how resizing a row after it appears pushes content and misaligns scroll targets, and recommends a custom Layout for exactly this kind of measurement-driven sizing.
  • Expecting laziness. A custom layout receives all of its subviews and measures them. For thousands of items in a scroll view, use a lazy stack or grid and keep your custom layout for the contents of each row.
  • Returning the proposal. A container that echoes back proposal.replacingUnspecifiedDimensions() claims space it doesn’t use and breaks when proposed .infinity.

Checklist

  • sizeThatFits returns a finite size for nil, 0, .infinity and concrete proposals.
  • One shared function computes the arrangement for both passes.
  • Placement starts at bounds.minX and bounds.minY, and each subview gets the size you measured as its proposal.
  • Default spacing comes from ViewSpacing unless the caller set a value.
  • A cache exists only if profiling asked for it, and it keys on every input it depends on.
  • Per-view options use LayoutValueKey with a convenience modifier.
  • Layout switches that should animate and keep state use AnyLayout.

Sources and further reading

Read next