Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 46 ยท Polish and Platform Features

Animations and Transitions

Learn SwiftUI animation: withAnimation, the animation(_:value:) modifier, springs, transitions, matchedGeometryEffect, phase and keyframe animators, and animatable data.

In SwiftUI you do not animate views. You change state, and SwiftUI animates the difference between the old and the new result of body. That one idea explains almost everything in this lesson. If a color changes from red to blue, SwiftUI can draw the in-between colors. If a view appears, SwiftUI can fade or slide it in. Your job is to say which change should be animated and how.

This lesson covers the two ways to switch animation on, the built-in curves and springs, transitions for views that appear and disappear, shared-element effects with matchedGeometryEffect, the newer phase and keyframe animators, and the Animatable protocol that makes custom values animate. It builds on state and bindings and view identity. The real SwiftUI code on this page is read-only because it needs a device or simulator; the runnable examples are small stand-ins that compute the same numbers an animation would use.

State changes, SwiftUI draws the frames

State changes You set a value, nothing else.
Diff SwiftUI compares old and new body.
Interpolate It computes the frames in between.

You describe the end state, never the individual frames.

1 / 2

Explicit animation with withAnimation

withAnimation wraps a state change. Every view whose appearance depends on that state change animates, and nothing else does.

Swift
struct ExpandingCard: View {
    @State private var isExpanded = false

    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: isExpanded ? 8 : 40)
                .fill(isExpanded ? Color.orange : Color.blue)
                .frame(width: 200, height: isExpanded ? 240 : 80)

            Button("Toggle") {
                withAnimation(.easeInOut(duration: 0.4)) {
                    isExpanded.toggle()
                }
            }
        }
    }
}

When you tap the button, isExpanded flips. The corner radius, the color and the height all depend on it, so all three animate together over 0.4 seconds. You wrote no code for the frames in between. Because the animation is attached to the change rather than to a view, it is called explicit animation. Use it in button actions, gesture handlers and anywhere you control the moment of the change.

withAnimation without arguments uses a default animation (a smooth spring on current systems), so withAnimation { isExpanded.toggle() } is often all you need. On iOS 17 and later you can also attach a completion handler, which runs when the animation finishes: withAnimation(.easeOut) { ... } completion: { ... }.

Implicit animation with animation(_:value:)

The animation(_:value:) modifier is implicit: it is attached to a view and says "whenever this value changes, animate the changes to me and my children".

Swift
Circle()
    .fill(isOn ? Color.green : Color.gray)
    .scaleEffect(isOn ? 1.2 : 1.0)
    .animation(.spring(duration: 0.5, bounce: 0.3), value: isOn)

The value: parameter matters. Without it, the modifier would animate on every change of any state, including ones you never meant to animate. That older form is deprecated. Always pass the value that should trigger the animation, and place the modifier after the properties you want animated, because modifiers only affect what is above them.

withAnimation .animation(_:value:)
Where you write it around the state change on the view
Scope everything that depends on the change that view and its children
Good for taps and gestures a single property that always animates

Both can be combined. Passing nil as the animation (transaction.animation = nil via .transaction) switches animation off for a subtree, which is useful when a parent animates but one child must jump.

Timing curves and springs

An animation is a function from time to progress. Classic curves are .linear, .easeIn, .easeOut and .easeInOut, each with an optional duration:. They start and stop along a fixed path.

Springs are the default choice for most interface motion because they feel physical and can be interrupted gracefully. Modern SwiftUI offers presets and a simple parameter pair:

  • .smooth, .snappy and .bouncy: ready-made springs with no overshoot, a little, and a lot.
  • .spring(duration: 0.5, bounce: 0.3): bounce is 0 for no overshoot, positive for bounce.
  • .spring(response:dampingFraction:): the older pair; damping 1 means no overshoot, below 1 means oscillation.
  • .interpolatingSpring(...): a spring that keeps its velocity when interrupted by a new animation.

You can modify any animation with .delay(_:), .speed(_:) and .repeatCount(_:autoreverses:) or .repeatForever(autoreverses:).

Since SwiftUI cannot run here, the first TryIt computes the progress curves directly. It samples an ease-in-out curve (a smoothstep, close to the real shape) and a damped spring, and draws each as a bar. Notice how the spring passes 100% and comes back.

Swift Easing curve versus spring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Both columns end near 100%, but the ease-in-out never goes past it, while the spring overshoots and settles. That overshoot is what the bounce value controls.

Transitions

Animating a property changes a view that stays. A transition describes how a view enters and leaves the screen when an if inserts or removes it.

Swift
struct Banner: View {
    @State private var showsBanner = false

    var body: some View {
        VStack {
            Button("Show banner") {
                withAnimation(.snappy) { showsBanner.toggle() }
            }

            if showsBanner {
                Text("Saved!")
                    .padding()
                    .background(.green, in: Capsule())
                    .transition(.move(edge: .top).combined(with: .opacity))
            }
        }
    }
}

Two rules make transitions work. First, the insertion or removal must happen inside an animation, such as withAnimation here. Without it the banner simply pops in. Second, the .transition modifier belongs on the view that appears and disappears, not on its container.

Built-in transitions include .opacity (the default), .scale, .slide, .move(edge:), .offset(x:y:) and .push(from:). Combine them with .combined(with:). Use .asymmetric(insertion:removal:) when entering and leaving should differ, for example sliding in from the trailing edge but fading out.

Changing a view's .id(_:) also counts as removing the old view and inserting a new one, so a transition plays. That is how a counter can slide the old number out and the new one in.

Transitions are a before/after model

A transition really describes two states of a view: how it looks while not in the hierarchy, and how it looks while in it. An opacity transition is "transparent when absent, fully visible when present". SwiftUI then animates between them. The second TryIt models that: given an insertion progress from 0 to 1, it computes opacity, scale and offset for a combined transition.

Swift A combined transition as numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The values are plain interpolation between two appearances. Removal simply plays the same range in reverse, which is why most transitions are symmetric by default.

Shared elements with matchedGeometryEffect

Sometimes a view should look like it moves from one place to another, for example a thumbnail growing into a detail card. matchedGeometryEffect(id:in:) links two views that never exist at the same time, so SwiftUI treats them as one view travelling.

Swift
struct Selector: View {
    @Namespace private var selectionSpace
    @State private var selected = 0
    let titles = ["Day", "Week", "Month"]

    var body: some View {
        HStack {
            ForEach(titles.indices, id: \.self) { index in
                Text(titles[index])
                    .padding(8)
                    .background {
                        if selected == index {
                            Capsule()
                                .fill(.blue.opacity(0.3))
                                .matchedGeometryEffect(id: "highlight", in: selectionSpace)
                        }
                    }
                    .onTapGesture {
                        withAnimation(.snappy) { selected = index }
                    }
            }
        }
    }
}

All Capsule views share the id "highlight" in one @Namespace. Only one exists at a time, so when selected changes, SwiftUI slides the capsule from the old label to the new one. Keep ids unique within a namespace for views that appear together. For navigation, newer systems also offer matchedTransitionSource with a zoom navigation transition, which produces the app-opening effect without a manual namespace dance.

Phase and keyframe animators

Sometimes you want a sequence: pulse, then settle, then pause. Chaining withAnimation calls with delays is fragile. Since iOS 17 there are two purpose-built tools.

phaseAnimator steps a view through a list of phases and applies a modifier for each:

Swift
Image(systemName: "heart.fill")
    .font(.largeTitle)
    .phaseAnimator([1.0, 1.4, 1.0]) { content, scale in
        content.scaleEffect(scale)
    } animation: { _ in
        .bouncy
    }

This pulses forever. Pass a trigger: to run the sequence once per change of a value instead.

keyframeAnimator gives full control over several properties on a timeline. You describe an initial value, then tracks of keyframes for each property:

Swift
struct Values {
    var scale = 1.0
    var rotation = 0.0
}

Image(systemName: "bell.fill")
    .keyframeAnimator(initialValue: Values(), trigger: ringCount) { content, values in
        content
            .scaleEffect(values.scale)
            .rotationEffect(.degrees(values.rotation))
    } keyframes: { _ in
        KeyframeTrack(\.scale) {
            CubicKeyframe(1.3, duration: 0.15)
            SpringKeyframe(1.0, duration: 0.4)
        }
        KeyframeTrack(\.rotation) {
            LinearKeyframe(15, duration: 0.1)
            LinearKeyframe(-15, duration: 0.1)
            SpringKeyframe(0, duration: 0.3)
        }
    }

Tracks run in parallel; keyframes inside a track run one after another. The keyframe kinds differ in how they reach the target: LinearKeyframe straight, CubicKeyframe with a smooth curve, SpringKeyframe with spring physics, and MoveKeyframe jumps instantly. Use phaseAnimator for simple repeating sequences and keyframeAnimator when several values need their own timelines.

Animatable data

How does SwiftUI interpolate a Color or a corner radius? Through the Animatable protocol. A type exposes an animatableData value that supports arithmetic (VectorArithmetic), and SwiftUI animates that value by interpolating between the start and end.

Swift
struct Wedge: Shape {
    var percent: Double

    var animatableData: Double {
        get { percent }
        set { percent = newValue }
    }

    func path(in rect: CGRect) -> Path {
        // Draw a pie slice that covers `percent` of the circle.
        Path()
    }
}

Because Wedge declares animatableData, changing percent inside withAnimation redraws the shape with every in-between value. Without it, the shape would jump to the final state, because SwiftUI cannot guess how to interpolate your arbitrary property. To animate two values at once, use AnimatablePair<Double, Double>.

Text can use .contentTransition(.numericText()) so changing digits roll smoothly, and SF Symbols have symbolEffect for bounces and pulses. Both are one-line upgrades that need no custom animatable code.

Respect reduced motion

Some people feel sick from large motion. The system exposes the setting, and well-made apps honor it:

Swift
@Environment(\.accessibilityReduceMotion) private var reduceMotion

withAnimation(reduceMotion ? nil : .bouncy) {
    isExpanded.toggle()
}

With reduced motion on, prefer fades or no animation instead of sliding, spinning or zooming. Passing nil removes the animation while keeping the state change. See accessibility and localization for the wider picture.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between withAnimation and animation(_:value:)?

    withAnimation wraps the change itself and affects all views depending on it. animation(_:value:) is attached to a view and reacts to one watched value.
  2. 2. A view appears with an if, but it pops in instead of sliding. What is the most likely cause?

    A transition only plays when the insertion or removal happens within an animation, for example inside withAnimation.
  3. 3. Which spring parameter controls how much a spring overshoots in spring(duration:bounce:)?

    bounce is 0 for no overshoot and grows for more bounce. Duration only controls how long the motion takes.
  4. 4. Why does a custom Shape need animatableData?

    Without animatableData SwiftUI does not know how to compute in-between values, so the shape jumps to its final state.
  5. 5. When should you use keyframeAnimator instead of phaseAnimator?

    keyframeAnimator has parallel tracks, each with its own keyframes, so it suits choreographed multi-property motion.

Summary

  • SwiftUI animates the difference between two body results; you only change state.
  • withAnimation is explicit and covers every effect of a change; animation(_:value:) is implicit and tied to one watched value.
  • Springs (.smooth, .snappy, .bouncy, .spring(duration:bounce:)) are the usual default; classic curves are .easeInOut and friends.
  • Transitions animate a view entering or leaving, but only when the change happens inside an animation.
  • matchedGeometryEffect makes two views look like one moving element.
  • phaseAnimator and keyframeAnimator build sequences; animatableData lets custom values interpolate.
  • Honor accessibilityReduceMotion.

Next: Gestures, Shapes, Canvas and Charts.