Pocket How
SwiftUI

SwiftUI animations: transactions, PhaseAnimator, KeyframeAnimator and zoom transitions

iOS 17+, iPadOS 17+. Intermediate. By Cihat Salik, .

Short answer

Every state change runs inside a transaction, and an animation is just a value on that transaction. Use withAnimation for changes you trigger, animation(_:value:) for one view, phaseAnimator for a sequence of whole states, keyframeAnimator for properties on independent timelines, and navigationTransition(.zoom) for pushes and sheets on iOS 18 and later. Read accessibilityReduceMotion and tone large motion down.

The problem

SwiftUI makes the first animation trivial and the fifth one confusing. A badge animates when you didn’t ask it to. A list row slides in with a spring you set for a different view. A multi-step bounce needs three chained DispatchQueue delays that break when the user taps twice. All of this gets easier once you see that every SwiftUI animation goes through the same mechanism, and that the newer APIs are built on top of it.

The mechanism: transactions

When state changes, SwiftUI wraps the update in a Transaction. An animation is a property of that transaction. Apple’s documentation for withAnimation says exactly this: the function sets the animation you pass as the animation property of the current transaction. Views that change during that update read the transaction and interpolate the change if they can.

Fatbobman’s deep dive, The Secret to Flawless SwiftUI Animations, builds the whole topic on this idea. withAnimation is a convenience form of withTransaction, and the .animation modifier is a convenience form of .transaction. An explicit transaction starts at the root and reaches every view affected by the change.

That gives you two families.

Explicit animation: you decide at the source

import SwiftUI

struct DisclosureCard: View {
    @State private var isExpanded = false

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            Button(isExpanded ? "Hide details" : "Show details") {
                withAnimation(.smooth) {
                    isExpanded.toggle()
                } completion: {
                    print("Expanded:", isExpanded)
                }
            }
            if isExpanded {
                Text("Shipping takes three to five days.")
                    .transition(.opacity.combined(with: .move(edge: .top)))
            }
        }
        .padding()
    }
}

The completion form of withAnimation requires iOS 17. Apple’s documentation notes that the completion always runs exactly once, immediately if the change created no animations. Use it instead of a delay that guesses the duration.

Use explicit animation for changes caused by a user action or an event. Everything that depends on the changed state animates with the same curve, which is usually what you want for a layout change.

Implicit animation: you decide at the view

struct ProgressRing: View {
    let progress: Double

    var body: some View {
        Circle()
            .trim(from: 0, to: progress)
            .stroke(.tint, style: StrokeStyle(lineWidth: 8, lineCap: .round))
            .rotationEffect(.degrees(-90))
            .animation(.snappy, value: progress)
            .frame(width: 60, height: 60)
    }
}

animation(_:value:) adds an animation to the transaction for this view and its children whenever value changes. Fatbobman points out the catch: if several properties change in the same update, views below the modifier can pick up the animation for a change they didn’t care about. Put the modifier as close as possible to the view that should animate, and pass the narrowest value.

Prefer explicit animation for user actions and implicit animation for views that display a value that can change from anywhere, like a progress ring fed by a download.

Turning animation off

To apply a change without animation even inside an animated context, give the update its own transaction:

func resetWithoutAnimation(_ apply: () -> Void) {
    var transaction = Transaction(animation: nil)
    transaction.disablesAnimations = true
    withTransaction(transaction, apply)
}

To stop one view from inheriting an animation, rewrite the transaction on that view (timestamp is a Date from your model):

Text(timestamp, style: .relative)
    .transaction { $0.animation = nil }

PhaseAnimator: a sequence of whole states

Some effects are a series of poses: pop, settle, rest. phaseAnimator (iOS 17+) animates through a list of phases in order, waiting for each animation to finish before starting the next. Natalia Panferova covers the API in Creating multi-step animations with PhaseAnimator: phases are typically a CaseIterable enum, the first case is the resting appearance, and the animation closure receives the phase being animated into, so each step gets its own curve.

import SwiftUI

enum SavePhase: CaseIterable {
    case rest, pop, settle

    var scale: Double {
        switch self {
        case .rest: 1
        case .pop: 1.25
        case .settle: 0.95
        }
    }

    var tilt: Angle {
        self == .pop ? .degrees(-8) : .zero
    }
}

struct SaveButton: View {
    @State private var saveCount = 0
    @Environment(\.accessibilityReduceMotion) private var reduceMotion

    var body: some View {
        Button("Save", systemImage: "checkmark.circle.fill") {
            saveCount += 1
        }
        .font(.title2)
        .phaseAnimator(SavePhase.allCases, trigger: reduceMotion ? 0 : saveCount) { content, phase in
            content
                .scaleEffect(phase.scale)
                .rotationEffect(phase.tilt)
        } animation: { phase in
            switch phase {
            case .pop: .bouncy(duration: 0.25)
            case .settle: .smooth(duration: 0.2)
            case .rest: .smooth(duration: 0.3)
            }
        }
    }
}

The trigger version runs the sequence each time the value changes. Natalia recommends an integer counter for events that can repeat, because a Boolean that flips back and forth can’t express “it happened again.” Without a trigger, the animator loops for as long as the view is on screen, which suits ambient effects like a pulsing recording indicator. She also notes the looping form can’t be stopped by a value, so to end it you swap in a view without the modifier.

The trigger expression reduceMotion ? 0 : saveCount stops the bounce entirely when Reduce Motion is on. The save still happens, and the button’s label already conveys it.

KeyframeAnimator: properties on separate timelines

Phases describe whole states that change together. When scale, rotation and offset each need their own timing, use keyframeAnimator (iOS 17+). The WWDC23 session Wind your way through advanced animations introduced it with this split: phases for chained states, keyframes when you need full control over timing.

You define a value type holding every animated property, then one KeyframeTrack per property.

import SwiftUI

struct HeartMotion {
    var scale: Double = 1
    var rotation: Angle = .zero
    var lift: Double = 0
}

struct LikeButton: View {
    @State private var likes = 0
    @Environment(\.accessibilityReduceMotion) private var reduceMotion

    var body: some View {
        Button {
            likes += 1
        } label: {
            Image(systemName: "heart.fill")
                .font(.largeTitle)
                .foregroundStyle(.pink)
                .keyframeAnimator(
                    initialValue: HeartMotion(),
                    trigger: reduceMotion ? 0 : likes
                ) { content, motion in
                    content
                        .scaleEffect(motion.scale)
                        .rotationEffect(motion.rotation)
                        .offset(y: motion.lift)
                } keyframes: { _ in
                    KeyframeTrack(\.scale) {
                        SpringKeyframe(1.35, duration: 0.18, spring: .bouncy)
                        SpringKeyframe(1, spring: .smooth)
                    }
                    KeyframeTrack(\.rotation) {
                        CubicKeyframe(.degrees(-14), duration: 0.1)
                        CubicKeyframe(.degrees(10), duration: 0.14)
                        CubicKeyframe(.zero, duration: 0.16)
                    }
                    KeyframeTrack(\.lift) {
                        LinearKeyframe(-12, duration: 0.15)
                        SpringKeyframe(0, duration: 0.45, spring: .bouncy)
                    }
                }
        }
        .accessibilityLabel("Like")
        .accessibilityValue("\(likes)")
    }
}

The four keyframe types decide how a track moves between values. The WWDC23 session describes them: LinearKeyframe interpolates in a straight line, SpringKeyframe pulls toward the target with a spring, CubicKeyframe follows a cubic curve and chains into smooth splines, and MoveKeyframe jumps with no interpolation. You can mix types within a track, and SwiftUI carries velocity across keyframes.

Three rules from Apple’s keyframeAnimator documentation shape how you use it:

  • The content closure runs on every frame while animating. Keep it to modifiers. No formatting, no lookups, no allocation.
  • If the trigger changes mid-animation, the keyframes closure receives the current interpolated value, and the new keyframes replace the old ones while keeping velocity. Rapid taps produce continuous motion instead of a restart.
  • When the animation ends, the animator stays at the final value, which becomes the starting value for the next run. End every track at the resting value unless you want the view to stay changed.

The session also warns that keyframes are predefined, closer to a video clip than a spring. They don’t retarget toward a moving goal the way a spring does, so use regular animations for anything driven by a gesture. For scrubbing or charts, KeyframeTimeline gives you the same tracks as a value you can sample at any time with value(time:).

matchedGeometryEffect: one view moving between places

matchedGeometryEffect(id:in:properties:anchor:isSource:) (iOS 14+) links the geometry of views that share an ID in a namespace. Apple’s documentation describes the core case: if you insert one view in the same transaction that removes another with the same key, SwiftUI interpolates their frames so it looks like one view moving. It links geometry only. How each view fades or scales is still up to its transition.

A selection indicator is the cleanest use:

import SwiftUI

struct FilterBar: View {
    private let filters = ["All", "Unread", "Flagged"]
    @State private var selected = "All"
    @Namespace private var indicator

    var body: some View {
        HStack(spacing: 4) {
            ForEach(filters, id: \.self) { filter in
                Button(filter) {
                    withAnimation(.snappy) { selected = filter }
                }
                .buttonStyle(.plain)
                .padding(.vertical, 8)
                .padding(.horizontal, 14)
                .background {
                    if selected == filter {
                        Capsule()
                            .fill(.tint.opacity(0.18))
                            .matchedGeometryEffect(id: "indicator", in: indicator)
                    }
                }
                .accessibilityAddTraits(selected == filter ? .isSelected : [])
            }
        }
    }
}

The documentation states that results are undefined unless exactly one view in the group has isSource set to true. Here only one capsule exists at a time, so that holds. The removal and insertion happen inside one withAnimation, which is what lets SwiftUI pair them. Change the selection without a transaction and the capsule jumps.

iOS 18 added navigationTransition(_:) and matchedTransitionSource(id:in:). Mark the tapped view as the source, put the zoom style on the destination, and the pushed view grows out of the source. The WWDC24 session Enhance your UI animations and transitions shows the same APIs working for sheet and fullScreenCover, and stresses that zoom transitions are continuously interactive: people can grab the view and drag it back at any point. Code around them has to tolerate a transition starting or reversing at any time.

Apple’s documentation says to apply navigationTransition to the destination view inside the stack or sheet, outside any container such as a VStack. With an iOS 17 deployment target, gate both modifiers:

import SwiftUI

struct Photo: Identifiable, Hashable {
    let id: Int
    let color: Color
}

struct PhotoGrid: View {
    let photos: [Photo]
    @Namespace private var zoom

    var body: some View {
        NavigationStack {
            ScrollView {
                LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))], spacing: 8) {
                    ForEach(photos) { photo in
                        NavigationLink(value: photo) {
                            RoundedRectangle(cornerRadius: 12)
                                .fill(photo.color)
                                .aspectRatio(1, contentMode: .fit)
                                .zoomSource(id: photo.id, in: zoom)
                        }
                        .accessibilityLabel("Photo \(photo.id)")
                    }
                }
                .padding()
            }
            .navigationDestination(for: Photo.self) { photo in
                photo.color
                    .ignoresSafeArea()
                    .zoomDestination(id: photo.id, in: zoom)
            }
        }
    }
}

extension View {
    @ViewBuilder
    func zoomSource(id: some Hashable, in namespace: Namespace.ID) -> some View {
        if #available(iOS 18, *) {
            matchedTransitionSource(id: id, in: namespace)
        } else {
            self
        }
    }

    @ViewBuilder
    func zoomDestination(id: some Hashable, in namespace: Namespace.ID) -> some View {
        if #available(iOS 18, *) {
            navigationTransition(.zoom(sourceID: id, in: namespace))
        } else {
            self
        }
    }
}

An if #available inside a @ViewBuilder is one of the few conditional modifiers that is safe: the condition can’t change while the app runs, so the view’s identity never flips.

iOS 26 extended matchedTransitionSource to toolbar items, so a sheet can zoom out of a toolbar button. iOS 27 adds CrossFadeNavigationTransition and AnyNavigationTransition, which lets you choose the transition at runtime. That makes a Reduce Motion variant a one-liner:

extension View {
    @ViewBuilder
    func calmZoom(id: some Hashable, in namespace: Namespace.ID, reduceMotion: Bool) -> some View {
        if #available(iOS 27, *) {
            navigationTransition(
                reduceMotion
                    ? AnyNavigationTransition(.crossFade)
                    : AnyNavigationTransition(.zoom(sourceID: id, in: namespace))
            )
        } else if #available(iOS 18, *) {
            navigationTransition(.zoom(sourceID: id, in: namespace))
        } else {
            self
        }
    }
}

Developers on Apple’s forums have reported glitches with zoom transitions during interrupted swipe-back gestures on several releases. Test the interactive dismissal, rapid back-and-forth taps and scrolling the grid right after returning, on the oldest OS you support.

Reduce Motion

accessibilityReduceMotion (iOS 13+) is true when the user turned on Reduce Motion. Apple’s description is specific: avoid large animations, especially ones that simulate depth. That doesn’t mean removing every animation. A cross-fade or a short opacity change is fine. Bounces, spins, parallax, zooms and anything that moves across the screen should be reduced or replaced.

Natalia Panferova’s advice for looping phase animations applies broadly: show static content under Reduce Motion and carry the meaning through text and accessibility labels. A small helper keeps that consistent for explicit animations:

func motion(_ animation: Animation, reduceMotion: Bool) -> Animation {
    reduceMotion ? .easeInOut(duration: 0.15) : animation
}

Then withAnimation(motion(.bouncy, reduceMotion: reduceMotion)) { ... } keeps the state change and swaps the motion for a short fade-like curve. For phase and keyframe animators, freeze the trigger as in the examples above.

Traps

  • Wide implicit animations. An .animation(_:value:) high in the tree animates everything below it. Attach it to the leaf that should move.
  • Animating identity changes. If a value change swaps an if/else branch, you get a transition, not an interpolation, and state inside resets. Animate a modifier on one view when you mean “the same view, changed.”
  • Delays instead of completions. DispatchQueue.main.asyncAfter guesses at durations. Use the withAnimation completion or a phase animator.
  • Expensive keyframe content. The content closure runs every frame. Treat it like a draw call.
  • Keyframes for gestures. Keyframes don’t retarget gracefully. Use springs for drags.
  • Two sources in a matched group. Keep exactly one isSource: true view per ID at a time.
  • Ignoring interruption. Zoom transitions can reverse mid-flight. Keep transition-related state minimal and reset it when the view appears or disappears.

Which API to use

You want Use Minimum OS
Animate the result of a tap or event withAnimation iOS 13
Run code when that animation finishes withAnimation(_:completionCriteria:_:completion:) iOS 17
A view animates whenever its value changes animation(_:value:) iOS 13
Apply a change with no animation withTransaction with disablesAnimations iOS 13
A sequence of whole states phaseAnimator(_:trigger:content:animation:) iOS 17
Properties on independent timelines keyframeAnimator(initialValue:trigger:content:keyframes:) iOS 17
One element moving between two places matchedGeometryEffect iOS 14
Push or sheet growing from its source navigationTransition(.zoom(sourceID:in:)) iOS 18
Choose the transition at runtime AnyNavigationTransition iOS 27

Sources and further reading

Read next