skip to content

In SwiftUI, when do you drive motion with TimelineView and its animation schedule instead of animating a state change?

level: middleimportance: should knowfreq 30%

answer

  1. no start and end state
  2. redraws at scheduled dates
  3. context.date as the clock
  4. animation, periodic, everyMinute, explicit
  5. minimumInterval and paused

basics

~20 s

Use TimelineView(.animation) when motion is a function of time with no end state, such as a scrolling waveform: it redraws its content on a schedule and passes context.date, from which you compute each frame yourself.

solid answer

~40 s

SwiftUI animations interpolate between two states, so they fit a change with a start and an end. Continuous motion, such as a rotating gradient, a waveform or a clock hand, has no end state; `TimelineView` (iOS 15) handles it by rebuilding its content at the dates a `TimelineSchedule` produces. `.animation` is a pausable schedule for continuous motion, `.periodic(from:by:)` gives a fixed interval, `.everyMinute` minute boundaries and `.explicit(_:)` a list you supply. Inside the closure you read `context.date`, derive elapsed time and compute positions, often drawing into a `Canvas`. `animation(minimumInterval:paused:)` caps the update rate and pauses it, and `context.cadence` tells you when the system updates less often than asked, so you can drop detail.

code

swift · 26 lines
swift
import SwiftUI

struct WaveformView: View {
    var isPlaying: Bool

    var body: some View {
        TimelineView(.animation(minimumInterval: 1.0 / 30, paused: !isPlaying)) { context in
            let time = CGFloat(context.date.timeIntervalSinceReferenceDate)
            Canvas { graphics, size in
                var path = Path()
                let midY = size.height / 2
                for x in stride(from: 0, through: size.width, by: 2) {
                    let angle = x / size.width * 4 * .pi + time * 3
                    let point = CGPoint(x: x, y: midY + sin(angle) * midY * 0.6)
                    if x == 0 {
                        path.move(to: point)
                    } else {
                        path.addLine(to: point)
                    }
                }
                graphics.stroke(path, with: .color(.accentColor), lineWidth: 2)
            }
        }
        .frame(height: 80)
    }
}

go deeper

for a junior

Recall that TimelineView redraws its content on a schedule and hands you context.date, and name the built-in schedules: animation, periodic, everyMinute and explicit.

for a middle

Explain why continuous motion with no end state does not fit state interpolation, and how you compute a frame from context.date, using minimumInterval, paused and cadence.

for a senior

Show you keep the per-update closure cheap, scope the timeline to the smallest view, pause it when idle, and combine it with Canvas or a sampled KeyframeTimeline.

for a principal

Weigh frame-driven drawing against interpolated animation and prebuilt assets for battery, maintenance and how easily designers can review the motion.

## Why state animation is not enough here SwiftUI's ordinary animations work on **differences between two states**. When a value changes inside `withAnimation`, or under an `animation(_:value:)` modifier, SwiftUI interpolates the animatable properties from the old state to the new one over the animation's duration, and then stops. That model fits a card expanding, a ring filling, a toggle sliding. Some motion has **no end state**: a waveform that scrolls while audio plays, a gradient that slowly rotates, the second hand of a clock, a particle field. You can fake some of these with `repeatForever(autoreverses:)`, but only when each cycle runs between two values SwiftUI can interpolate, such as a pulse or a full turn. When each frame is a function of elapsed time, the right tool is **`TimelineView`**, available since iOS 15. ## How TimelineView works `TimelineView` is a container with no appearance of its own. You give it a **schedule** (a type conforming to `TimelineSchedule`) and a content closure. Apple's documentation describes it as a view that "redraws the content it contains at scheduled points in time." The closure receives a `TimelineView.Context` with two members: - **`date`** — the date that triggered this update. You turn it into elapsed time (for example with `timeIntervalSinceReferenceDate`) and compute positions, angles or phases from it. - **`cadence`** — `.live`, `.seconds` or `.minutes`. The system may update more slowly than the schedule asks (a watch face with the wrist lowered is Apple's example), and the cadence lets you hide detail that would not be refreshed anyway, such as a second hand. Because you compute each frame yourself, nothing is interpolated for you: the content is simply rebuilt for each scheduled date. ## Choosing a schedule | Schedule | What it produces | Typical use | |---|---|---| | `.animation` / `.animation(minimumInterval:paused:)` | A pausable schedule that updates no more quickly than the interval you give | Continuous drawing and motion | | `.periodic(from:by:)` | Dates at a fixed interval from a start date | A timer that ticks once per second | | `.everyMinute` | The start of each minute | A clock without seconds | | `.explicit(_:)` | A finite or irregular list of dates you supply | Countdown milestones | Two details from the documentation matter in practice. For a schedule whose dates are all in the past, the view shows the last date; for one whose dates are all in the future, it draws with the current date until the first scheduled date arrives. ## Building frame-driven drawing A typical pattern pairs `TimelineView(.animation)` with **`Canvas`**, which draws paths immediately into a graphics context instead of building a view per element: 1. Read `context.date` once at the top of the closure and derive a time value. 2. Compute the shape for that instant (a sine wave offset by time, a hand angle from the seconds). 3. Draw it in the `Canvas` closure with `stroke` or `fill`. 4. Use `paused:` to stop updates when the motion is not needed, and `minimumInterval:` to cap how often it redraws. Keep the content closure light: it runs for every scheduled date, so formatting, allocation or model work inside it repeats at frame rate. Diagnosing that cost is part of the performance material. ## TimelineView next to the other custom-motion tools - **`Animatable`** lets SwiftUI interpolate your own shape or modifier between two states; TimelineView has no "between", only "now". - **`phaseAnimator`** steps through discrete states with animations between them; TimelineView computes continuous values from a clock. - **`KeyframeTimeline`** can be sampled at any time with `value(time:)`, so combining it with TimelineView lets you scrub or loop a scripted keyframe path from your own clock. ## Mistakes to avoid - Expecting `TimelineView` to interpolate like `withAnimation`; it only re-renders at scheduled dates. - Treating `.animation` as a guaranteed frame rate; `minimumInterval` is a lower bound on spacing, not a promise. - Wrapping a large part of a screen in a frame-paced timeline, so everything inside rebuilds every frame. - Leaving the schedule running when the motion is off screen or the feature is idle instead of passing `paused: true`. - Ignoring `cadence`, and drawing detail that the system will refresh only once a minute. - Reaching for `TimelineView` when the motion really has two end states; an ordinary animation, or an `Animatable` shape, is shorter and lets SwiftUI do the interpolation.

  • When would you still pick repeatForever over TimelineView for a looping effect?
    When the loop is a back-and-forth between two values SwiftUI can interpolate, such as an opacity pulse, `animation(.easeInOut.repeatForever(), value:)` is shorter and lets SwiftUI interpolate for you. TimelineView earns its place when each frame depends on elapsed time in a way two-state interpolation cannot express, or several values derive from one clock.
  • How can TimelineView and KeyframeTimeline work together?
    `KeyframeTimeline` describes a value's path over time and can be evaluated at any moment with `value(time:)` or `value(progress:)`. Inside a `TimelineView`, you compute elapsed time from `context.date` and sample the timeline, which lets you loop, scrub or synchronise a keyframed path with your own clock instead of a trigger.

  • TimelineView interpolates between two states the way withAnimation does.
  • The .animation schedule guarantees exactly the frame rate you request.
  • context.date is the time elapsed since the TimelineView appeared.
  • TimelineView arrived in iOS 17 together with PhaseAnimator.
  • Wrapping a whole screen in TimelineView(.animation) costs nothing extra.