Skip to content
Commitwise
Menu
iOS Development

SwiftUI layout and animation

Understand how SwiftUI sizes and places views (propose, choose, place), why modifier order matters, when to use ViewThatFits, GeometryReader, onGeometryChange or a custom Layout, and how animations, transitions, matchedGeometryEffect and view identity really work.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The designer’s mockup has a row of tags that wraps onto several lines, a price that grows when it changes, and a tab bar whose underline slides to the selected tab. The first attempt uses a GeometryReader that makes the row take the whole screen, the price jumps instead of animating, the underline fades instead of sliding, and the detail card sometimes appears with no animation at all.

SwiftUI layout and animation feel like magic until you know the two rules underneath: how a parent and a child agree on a size, and how SwiftUI decides that a view is the same view as before. With those, every layout and animation bug in this lesson has a predictable cause.

New to some of these? Open what you need, or skip ahead.

Basics:What is a view modifier?

A modifier is a method like .padding() or .background(.yellow) that wraps a view in a new view. Text("Hi").padding().background(.yellow) is a text, inside padding, inside a yellow background. Each modifier works on the result of everything before it, which is why order matters. See view modifierView modifierA method like .padding() or .background() in SwiftUI that wraps a view in a new view with a changed look or behavior.Open in glossary →.

Basics:What is @State?

@State is a value a SwiftUI view owns, like @State private var isOn = false. When it changes, SwiftUI updates the parts of the screen that read it. State belongs to the view’s identity: if SwiftUI decides the view is a new one, its state starts over.

Part Not started

How SwiftUI sizes and places views

Layout in SwiftUI is a short conversation, repeated down the tree:

  1. The parent offers a size: “You can have up to 390 by 200 points.”
  2. The child decides its own size: a Text takes just enough for its words; a Color takes everything offered; an Image takes its own size unless it’s resizable.
  3. The parent places the child inside its own area, centered by default.

The child always has the last word on its size. That explains most surprises:

  • .frame(width: 100) doesn’t resize the text: it’s a new view, 100 points wide, that offers 100 points to the text and centers it.
  • Modifier order matters. .padding().background(.yellow) colors the padding too; .background(.yellow).padding() colors only behind the text, then adds empty space around it.
  • Stacks give space first to children that can’t grow much, and share the rest. .layoutPriority(1) makes a child go first.

The layout protocol is propose, choose, place: a parent proposes a ProposedViewSize (each dimension can be a value, nil for “your ideal size”, 0 or infinity), the child returns its size, and the parent positions it. Modifiers are views, so .frame, .padding and .fixedSize() are layout participants that change proposals; fixedSize() proposes nil (ideal size) in one or both axes. HStack divides space by sorting children by flexibility (the range between their minimum and maximum size for the proposal) and by layoutPriority, offering the least flexible first. GeometryReader is greedy (it accepts the whole proposal) and places its content at the top-leading corner, which is why it breaks layouts when used for measuring; measure with onGeometryChange(for:of:action:) or a background GeometryReader instead. ViewThatFits picks the first child whose ideal size fits. The Layout protocol (iOS 16) gives you the same primitives: sizeThatFits and placeSubviews, with optional caching.

struct FlowLayout: Layout {
    var spacing: CGFloat = 8

    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
        let rows = arrange(maxWidth: proposal.width ?? .infinity, subviews: subviews)
        let width = rows.map(\.width).max() ?? 0
        let height = rows.last.map { $0.y + $0.height } ?? 0
        return CGSize(width: proposal.width ?? width, height: height)
    }

    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
        for row in arrange(maxWidth: bounds.width, subviews: subviews) {
            for item in row.items {
                subviews[item.index].place(at: CGPoint(x: bounds.minX + item.x, y: bounds.minY + row.y),
                                           proposal: .unspecified)
            }
        }
    }

    private struct Row {
        var items: [(index: Int, x: CGFloat)] = []
        var y: CGFloat = 0
        var width: CGFloat = 0
        var height: CGFloat = 0
    }

    private func arrange(maxWidth: CGFloat, subviews: Subviews) -> [Row] {
        var rows = [Row()]
        var x: CGFloat = 0
        for (index, subview) in subviews.enumerated() {
            let size = subview.sizeThatFits(.unspecified)          // each tag's ideal size
            if x > 0, x + size.width > maxWidth {                   // doesn't fit: start a new row
                let y = rows[rows.count - 1].y + rows[rows.count - 1].height + spacing
                rows.append(Row(y: y))
                x = 0
            }
            rows[rows.count - 1].items.append((index, x))
            rows[rows.count - 1].height = max(rows[rows.count - 1].height, size.height)
            rows[rows.count - 1].width = x + size.width
            x += size.width + spacing
        }
        return rows
    }
}

// Use it like a stack
FlowLayout {
    ForEach(recipe.tags, id: \.self) { tag in
        Text(tag).padding(.horizontal, 10).padding(.vertical, 4)
            .background(.thinMaterial, in: Capsule())
    }
}

// Two layouts, SwiftUI picks the first one that fits
ViewThatFits(in: .horizontal) {
    HStack { price; addToCartButton }
    VStack(alignment: .leading) { price; addToCartButton }
}
  • sizeThatFits answers “how big are you, if offered this much?”. The layout lays out the tags in rows and reports the total height.
  • placeSubviews puts each tag at its position, row by row.
  • subview.sizeThatFits(.unspecified) asks each tag for its natural size, the same question a stack asks.
  • ViewThatFits tries the HStack first and falls back to the VStack on narrow screens or with large text sizes.

Predict the output

Text("Sale").background(.yellow).padding(20) and Text("Sale").padding(20).background(.yellow). How do they look different?

Practice: a row that doesn’t squeeze the price

Spot the bugThe price gets cut off

Tap the line with the bug.

HStack {
    Text(product.name)
        .font(.headline)
    Spacer()
    Text(product.price, format: .currency(code: "EUR"))
        .font(.headline)
}

Exercisemedium

Measure without breaking the layout

A collapsible text shows “Read more” only when the full text is taller than three lines. You need the full text’s height. A teammate wrapped the text in a GeometryReader, and now it fills the whole screen. What would you do instead?

›

There’s a modifier that reports a size to you without taking part in the layout.

SolutionTry it yourself first

Keep the text’s normal layout and read its size with onGeometryChange:

@State private var fullHeight: CGFloat = 0

Text(article.body)
    .fixedSize(horizontal: false, vertical: true)       // full height, not truncated
    .onGeometryChange(for: CGFloat.self) { proxy in
        proxy.size.height
    } action: { height in
        fullHeight = height
    }

GeometryReader takes all the space offered and puts its content in the top-left corner, so it changes the layout it’s trying to measure. onGeometryChange only reports.

Layout details worth knowing

  • Alignment guides: .alignmentGuide(.firstTextBaseline) { … } and custom AlignmentIDs align views across different stacks (a label column, icons on baselines).
  • Layout caching: Layout can declare a Cache type and compute measurements once in makeCache; updateCache runs when subviews change. Worth it for large flows.
  • AnyLayout switches between HStackLayout and VStackLayout (for example on dynamicTypeSize) while keeping subview identity, so the switch can animate.
  • Safe areas and containerRelativeFrame (iOS 17) size views relative to the nearest container, such as paging cards at 80% of the scroll view’s width, without a GeometryReader.
  • Propose → choose → place; the child decides its size. Proposals can be nil (ideal), 0 or infinity.
  • Modifiers are views: order changes layout. .frame proposes and aligns; fixedSize() proposes nil.
  • Stacks offer space least-flexible first, adjusted by layoutPriority.
  • GeometryReader is greedy and top-leading: measure with onGeometryChange instead. ViewThatFits for fallbacks, AnyLayout to switch stacks with identity preserved, containerRelativeFrame for container-relative sizes.
  • Custom Layout: sizeThatFits + placeSubviews, optional cache.

Check this part

  1. Who decides a Text’s final size in SwiftUI?

  2. Why does wrapping a row in GeometryReader often make it fill the screen?

  3. What does fixedSize() change?

  4. Which tool switches between an HStack and a VStack while keeping subview identity?

Layout is a negotiation: the parent proposes a size, the child picks its own size, the parent places it. Modifiers wrap views, so order changes the result. Stacks share space by flexibility and layoutPriority; fixedSize ignores the proposal. Prefer ViewThatFits and onGeometryChange over GeometryReader, which takes all offered space. For custom arrangements, write a Layout with sizeThatFits and placeSubviews.

Part Not started

Animations, transitions and identity

SwiftUI animates changes. You change some state, SwiftUI computes the screen before and after, and moves between them smoothly. There are two ways to say “animate this change”:

  • withAnimation { isExpanded.toggle() } animates everything that changes because of that state change.
  • .animation(.spring, value: isExpanded) on a view animates that view whenever isExpanded changes.

A transition is different: it’s how a view appears or disappears, for example sliding in when an if becomes true. It only plays when the change happens inside an animation.

SwiftUI also needs to know which view is “the same” before and after. That’s the view’s identityView identity (SwiftUI)How SwiftUI decides a view is the same view as before: by its position in the code or by an explicit id.Open in glossary →: its position in the code (structural identity) or an explicit .id(...). Same identity: SwiftUI animates its properties (size, color, position). New identity: the old view is removed, a new one inserted, with transitions, and its @State starts fresh.

An animation is a Transaction carrying an Animation, attached to a state change (withAnimation) or scoped to a value (.animation(_:value:), preferably with the iOS 17 .animation(_:body:) form to limit what it affects). SwiftUI interpolates animatable data of views with the same identity: built-in modifiers conform to Animatable; custom shapes and modifiers expose animatableData (use AnimatablePair for several values). Transitions apply only to insertion and removal, which requires an identity change: an if branch, a ForEach element added or removed, or a new .id. matchedGeometryEffect interpolates frames between two views sharing an id in a Namespace, one of which is usually being inserted while the other is removed. contentTransition(.numericText(value:)) and symbol effects animate content changes within one view. iOS 17 added PhaseAnimator and KeyframeAnimator for multi-step animations, and spring animations defined by duration and bounce are the default. Always check accessibilityReduceMotion for large movements.

struct FavoriteButton: View {
    @Binding var isFavorite: Bool
    let count: Int

    var body: some View {
        Button {
            withAnimation(.spring(duration: 0.35, bounce: 0.4)) { isFavorite.toggle() }
        } label: {
            HStack {
                Image(systemName: isFavorite ? "heart.fill" : "heart")
                    .contentTransition(.symbolEffect(.replace))       // the symbol morphs
                Text(count, format: .number)
                    .contentTransition(.numericText(value: Double(count)))   // digits roll
            }
        }
    }
}

struct CategoryTabs: View {
    @Binding var selection: Category
    @Namespace private var underline

    var body: some View {
        HStack {
            ForEach(Category.allCases) { category in
                Button(category.title) {
                    withAnimation(.snappy) { selection = category }
                }
                .padding(.vertical, 8)
                .overlay(alignment: .bottom) {
                    if selection == category {
                        Capsule().frame(height: 3)
                            .matchedGeometryEffect(id: "underline", in: underline)   // one underline, moving
                    }
                }
            }
        }
    }
}

struct RecipeCard: View {
    let recipe: Recipe
    @State private var showsSteps = false
    @Environment(\.accessibilityReduceMotion) private var reduceMotion

    var body: some View {
        VStack(alignment: .leading) {
            Button(showsSteps ? "Hide steps" : "Show steps") {
                withAnimation(reduceMotion ? nil : .smooth) { showsSteps.toggle() }
            }
            if showsSteps {
                StepsList(steps: recipe.steps)
                    .transition(.move(edge: .top).combined(with: .opacity))   // plays on insert and remove
            }
        }
        .clipped()
    }
}
  • withAnimation around the state change animates everything it affects: the heart symbol and the number.
  • matchedGeometryEffect says “these underlines are the same thing”. When the selected tab changes, one underline is removed and another inserted, and SwiftUI moves a single underline between them instead of fading.
  • .transition only plays because showsSteps changes inside withAnimation. Without it, the steps would just appear.
  • Reduce Motion: passing nil as the animation turns it off for people who asked for less movement in Settings.
Spot the bugThe steps appear with no animation

Tap the line with the bug.

struct RecipeCard: View {
    @State private var showsSteps = false

    var body: some View {
        VStack {
            Button("Show steps") {
                showsSteps.toggle()
            }
            if showsSteps {
                StepsList()
                    .transition(.slide)
            }
        }
    }
}

Production puzzles

Predict the output

A list row is written as RowView(item: item).id(UUID()) inside a ForEach, "to make it refresh". RowView has @State private var isExpanded = false. The user expands a row, then a background refresh updates an unrelated property on the screen. What happens to the expanded row?

Spot the bugA layout loop through state

Tap the line with the bug.

struct ChatInput: View {
    @State private var height: CGFloat = 40
    @Binding var text: String

    var body: some View {
        GeometryReader { proxy in
            TextEditor(text: $text)
                .onChange(of: proxy.size.height) { _, newHeight in
                    height = newHeight + 16
                }
        }
        .frame(height: height)
    }
}

Exercisehard

A hero transition from a grid to a detail

A photo grid opens a full-screen detail where the tapped photo grows from its grid position. Design it, and say what goes wrong with a naive matchedGeometryEffect across NavigationStack and .sheet.

›

matchedGeometryEffect works within one view hierarchy, and only while both views are part of the same animated update. iOS 18 added a navigation transition for exactly this case.

SolutionTry it yourself first
  • iOS 18+: use the zoom navigation transition: .matchedTransitionSource(id: photo.id, in: namespace) on the grid cell and .navigationTransition(.zoom(sourceID: photo.id, in: namespace)) on the destination, pushed with NavigationStack or presented with fullScreenCover. It’s interactive (swipe down to shrink back) and handles the hierarchy boundary.
  • Custom, same hierarchy: keep grid and detail in one ZStack, show the detail with if let selected, give the image matchedGeometryEffect(id: photo.id, in: ns) in both places with isSource set correctly, and change selected inside withAnimation. Hide the grid cell’s image while the detail shows it, or both are visible mid-animation.
  • Naive approach failure: matchedGeometryEffect across a NavigationStack push or a sheet does nothing useful, because the destination lives in a different hierarchy and isn’t inserted in the same transaction.
  • Polish: load a thumbnail first and swap in the full image after the animation; respect Reduce Motion with a crossfade.
Exerciseeasy

Animate a counter

A cart badge shows the number of items. When the number changes, the digits should roll instead of jumping, and the badge should pop slightly. Write the view.

›

One modifier animates text content; a scale effect driven by state can make the pop.

SolutionTry it yourself first
struct CartBadge: View {
    let count: Int

    var body: some View {
        Text(count, format: .number)
            .contentTransition(.numericText(value: Double(count)))
            .font(.caption.bold())
            .padding(6)
            .background(.red, in: Capsule())
            .foregroundStyle(.white)
            .animation(.spring(duration: 0.3, bounce: 0.5), value: count)
            .phaseAnimator([1.0, 1.25, 1.0], trigger: count) { view, scale in
                view.scaleEffect(scale)
            }
    }
}

.animation(_:value:) animates the digit change whenever count changes, and phaseAnimator runs the scale through 1.0 → 1.25 → 1.0 on each change.

  • Animations interpolate animatable data across a state change with the same identity: withAnimation (transaction) or .animation(_:value:) / .animation(_:body:) (scoped).
  • Transitions need insertion/removal (identity change) inside an animated transaction.
  • matchedGeometryEffect within one hierarchy; iOS 18 zoom navigation transition across navigation/covers.
  • contentTransition(.numericText), symbol effects, PhaseAnimator, KeyframeAnimator; custom Animatable via animatableData.
  • .id changes reset state and replay transitions; never .id(UUID()) in body. Respect Reduce Motion.

Check this part

  1. A view has .transition(.slide) but just pops in. What’s missing?

  2. What happens to a view’s @State when its .id changes?

  3. Why doesn’t matchedGeometryEffect animate between a grid and a pushed detail screen?

  4. What does .id(UUID()) inside a ForEach row do?

Animations interpolate between two states of the same view: trigger them with withAnimation or .animation(_:value:). Transitions animate a view being inserted or removed, so they need an identity change (an if, or a new .id) inside an animated update. matchedGeometryEffect moves one view between two places; contentTransition animates text and symbol changes. Changing .id resets state. Respect Reduce Motion.

Key takeaways

  • The parent offers a size, the child picks its size, the parent places it.
  • Modifier order matters; read modifiers from the inside out.
  • Measure with onGeometryChange instead of wrapping views in GeometryReader.
  • Animate state changes with withAnimation; transitions need an if or a new identity.
  • Changing .id resets a view’s state.
  • Reason about proposals, flexibility and priority; reach for Layout, ViewThatFits and AnyLayout before geometry hacks.
  • Identity drives both state lifetime and transitions; keep it stable and change it on purpose.
  • Scope animations tightly; use content transitions and matched geometry for continuity.
  • Avoid geometry-to-state feedback loops; respect Reduce Motion.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.