skip to content

In SwiftUI, how would you script a mascot hop with keyframeAnimator, and how do its tracks differ from phaseAnimator steps?

level: seniorimportance: should knowfreq 25%

answer

  1. a path over time, not states
  2. one Animatable value struct
  3. a KeyframeTrack per key path
  4. linear, spring, cubic, move
  5. stays at the end value

basics

~20 s

keyframeAnimator (iOS 17) animates a value struct along scripted tracks: each KeyframeTrack targets one key path with its own LinearKeyframe, SpringKeyframe, CubicKeyframe or MoveKeyframe timings, whereas phaseAnimator moves every property together from one phase to the next.

solid answer

~40 s

I'd define a struct with `verticalOffset`, `verticalStretch` and `angle`, and apply `keyframeAnimator(initialValue:trigger:content:keyframes:)` with a tap counter as the trigger. The content closure gets a proxy and the interpolated value and applies `offset`, `scaleEffect` and `rotationEffect`; it runs every frame, so it stays cheap. In the keyframes closure each `KeyframeTrack(\.property)` lists its own keyframes: a `CubicKeyframe` squash, a `SpringKeyframe` up, a `MoveKeyframe` where a value should jump, each with a duration, so stretch and rise run on independent timings. A `phaseAnimator` instead has discrete states that animate together with one `Animation` per step. Two traps: the animator stays at the end value, which seeds the next run, so tracks should end at rest; and a retrigger mid-flight restarts from the current value, keeping its velocity.

code

swift · 38 lines
swift
import SwiftUI

struct HopValues {
    var verticalOffset = 0.0
    var verticalStretch = 1.0
    var angle = Angle.zero
}

struct MascotView: View {
    @State private var hops = 0

    var body: some View {
        Image(systemName: "hare.fill")
            .font(.largeTitle)
            .keyframeAnimator(initialValue: HopValues(), trigger: hops) { content, value in
                content
                    .rotationEffect(value.angle)
                    .scaleEffect(y: value.verticalStretch, anchor: .bottom)
                    .offset(y: value.verticalOffset)
            } keyframes: { _ in
                KeyframeTrack(\.verticalStretch) {
                    CubicKeyframe(0.8, duration: 0.1)
                    CubicKeyframe(1.15, duration: 0.2)
                    SpringKeyframe(1.0, duration: 0.3, spring: .bouncy)
                }
                KeyframeTrack(\.verticalOffset) {
                    LinearKeyframe(0, duration: 0.1)
                    SpringKeyframe(-60, duration: 0.25, spring: .bouncy)
                    CubicKeyframe(0, duration: 0.3)
                }
                KeyframeTrack(\.angle) {
                    CubicKeyframe(.degrees(-8), duration: 0.2)
                    CubicKeyframe(.zero, duration: 0.4)
                }
            }
            .onTapGesture { hops += 1 }
    }
}

go deeper

for a junior

Recall that keyframeAnimator plays scripted tracks when a trigger changes, and that each KeyframeTrack animates one property of a value struct.

for a middle

Explain the four keyframe types, how tracks run side by side on their own timings, and how this differs from phaseAnimator's discrete states.

for a senior

Show you end tracks at rest, know that a retrigger restarts from the current value with velocity preserved, and keep the per-frame content closure cheap.

for a principal

Judge when scripted keyframes in code beat designer-made animation assets for maintenance, review and runtime cost across a product.

## Phases versus keyframes SwiftUI (since iOS 17) offers two animators for multi-step motion, and the interview question is usually which one and why. - A **phase animator** moves through **discrete states**. Each phase sets a group of modifier values, and SwiftUI animates the whole group from one phase to the next with one `Animation` per step. Every property moves together. - A **keyframe animator** describes **the path a value takes over time**. Apple's `KeyframeTimeline` documentation puts it plainly: unlike other SwiftUI animations, keyframes "don't interpolate between from and to values that SwiftUI provides as state changes. Instead, keyframes fully define the path that a value takes over time." A mascot hop shows the difference. The squash before the jump, the rise, the stretch in the air, and a small wiggle at the top all start and end at different times. Phases cannot express that without many artificial steps; keyframes can, because each property gets its own **track**. ## The pieces of keyframeAnimator You apply `keyframeAnimator(initialValue:trigger:content:keyframes:)` to the view, or the `repeating:` variant to loop continuously: 1. **A value type.** A struct holding the properties to move, such as `verticalOffset`, `verticalStretch` and `angle`. Each property a track targets must be `Animatable`; `Double`, `CGFloat`, `CGPoint` and `Angle` all qualify. 2. **`initialValue`.** The value the animator starts from on first appearance. 3. **`trigger`.** Any `Equatable` value; a tap counter makes every tap play the keyframes. 4. **`content`.** A closure receiving a proxy for the view and the current interpolated value; you apply `offset`, `scaleEffect`, `rotationEffect` from it. Apple warns that this closure is updated **on every frame** while animating, so it must stay cheap. The closure is also declared `@Sendable`, so anything it captures must be `Sendable`; working only from the proxy and the value keeps it simple. 5. **`keyframes`.** A builder closure that receives the current value and returns tracks. ## Tracks and keyframe types Each **`KeyframeTrack`** takes a key path into the value type and a list of keyframes for that one property. Tracks run side by side, each on its own timing. Inside a track you mix four keyframe types: | Keyframe | Interpolation | Notes | |---|---|---| | `LinearKeyframe` | Straight line, optional `timingCurve` | Constant speed or a unit curve | | `SpringKeyframe` | A `Spring` such as `.bouncy` | `duration` is optional | | `CubicKeyframe` | Cubic curve | Adjacent cubic keyframes form a Catmull-Rom spline; velocities are computed if you omit them | | `MoveKeyframe` | None | Jumps immediately to the value | SwiftUI preserves velocity between keyframes inside a track, so a spring that follows a cubic keyframe starts with the speed the curve ended with. If two tracks target the same property, Apple's documentation says the value from the **last** competing track is used. ## The two behaviours that bite in production **The animator stays where it ends.** The documentation states that when a keyframe animation finishes, "the animator will remain at the end value, which becomes the initial value for the next animation." A track whose last keyframe is not the rest value leaves the mascot tilted or lifted, and the next hop starts from there. End every track at its resting value, or read the `keyframes` closure's argument (the current value) on purpose. **A retrigger replaces the running animation.** If the trigger changes while keyframes are playing, the `keyframes` closure is called with the **current interpolated value**, and the returned keyframes replace the old ones. Velocity is preserved, so cubic and spring keyframes without an explicit start velocity continue smoothly. Rapid taps therefore restart the hop mid-air rather than queueing hops. ## Using keyframes outside the animator A `KeyframeTimeline` built from the same tracks can be evaluated directly with `value(time:)` or `value(progress:)`, and it reports its `duration`. That allows scrubbing a keyframed path with a gesture or sampling it inside a `TimelineView`, while the animator remains the right tool for "play this when that changes". ## Review checklist - Does the motion need independent timings per property? Choose keyframes; otherwise phases are simpler. - Is every track's final keyframe the resting value? - Is the `content` closure free of formatting, allocation and model work? - Should a retrigger restart the motion, or should taps be ignored while it plays? - Does a looping `repeating:` animator respect Reduce Motion, a concern covered with accessibility?

  • Why does the mascot stay slightly tilted after a hop?
    The animator remains at the end value of the keyframes, and that value becomes the starting point of the next run. If the angle track's last keyframe is not `.zero`, the tilt persists and the next hop starts tilted. End each track at its resting value.
  • What happens when the user taps again mid-hop?
    The trigger changes, so SwiftUI calls the `keyframes` closure with the current interpolated value and replaces the running keyframes with the new ones. Velocity carries over, so cubic and spring keyframes without a custom start velocity continue smoothly instead of snapping.

Keyframe tracks are like the lanes of a video editor: scale, position and rotation each sit in their own lane with clips of their own lengths, and the playhead reads every lane at once. A phase animator is closer to a slideshow that animates from one whole slide to the next.

  • Each KeyframeTrack plays after the previous track finishes.
  • keyframeAnimator resets to initialValue after every run.
  • The content closure runs once per trigger, so heavy work there is fine.
  • Keyframes need withAnimation around the trigger change to play.
  • keyframeAnimator can only animate CGFloat values.