skip to content

Animating State Changes

SwiftUI animates state changes, not views: implicit and explicit animation, transitions, matched geometry and scripted motion. Interviewers ask what animates and why a change sometimes jumps.

on this pageshow

explore

questions

16

In SwiftUI, how do you make a view fade or slide in and out when it is shown or hidden with transition(_:)?

level: juniorimportance: must knowfreq 70%

answer

  1. arrival and departure, not a property change
  2. a conditional view inside an if
  3. transition(_:) on that view
  4. toggle inside withAnimation

basics

~10 s

Show the view inside an if, attach transition(.opacity) or transition(.move(edge: .top)) to it, and toggle the Boolean inside withAnimation. SwiftUI then animates the view in on insertion and out on removal.

solid answer

~30 s

A transition describes how a view enters and leaves the hierarchy, so the view must actually come and go: wrap it in `if showBanner { ... }`. Attach `.transition(.opacity)`, `.transition(.move(edge: .top))`, `.transition(.scale)` or `.transition(.slide)` to the conditional view, and combine two effects with `combined(with:)`, for example `.move(edge: .top).combined(with: .opacity)`. Then make the change animated with `withAnimation { showBanner.toggle() }`, or with `animation(_:value:)` on a container that is on screen in both states. Without an animation the view simply pops in and out; without the `if` there is no insertion for the transition to play on.

code

swift · 20 lines
swift
struct SavedBanner: View {
    @State private var showBanner = false

    var body: some View {
        VStack {
            if showBanner {
                Text("Saved")
                    .padding()
                    .background(.green, in: .capsule)
                    .transition(.move(edge: .top).combined(with: .opacity))
            }
            Spacer()
            Button("Save") {
                withAnimation {
                    showBanner.toggle()
                }
            }
        }
    }
}

go deeper

for a junior

Recall the three pieces: a view inside an if, a transition(_:) on that view, and a state change wrapped in withAnimation. Name opacity, move(edge:), scale and slide.

for a middle

Explain that a transition only describes insertion and removal and that the animation comes from the transaction. Show combined(with:) and where animation(_:value:) must sit to see both states.

for a senior

Diagnose a transition that never plays by checking each piece in turn: is the view really removed, is the change animated, is the modifier on the right view. Mention what replaced the deprecated value-less animation.

for a principal

Frame transitions as part of a team's motion vocabulary: a small set of shared transitions applied consistently beats ad hoc effects per screen, and reviewers should check that each one is attached to a view that truly comes and goes.

## What a transition is In SwiftUI a **transition** describes how a view *enters* and *leaves* the view hierarchy. It is not an animation by itself: it says what the view looks like just before it is inserted and just after it is removed, and the current animation carries the view between that look and its normal appearance. You attach one with the `transition(_:)` modifier. Apple's documentation for the modifier says it plainly: when this view appears or disappears, the transition is applied to it, allowing it to animate in and out. That definition explains almost every beginner surprise. A transition only has something to do when a view *appears* or *disappears*. A view that stays on screen and merely changes its opacity, offset or color is animated by those modifiers, not by its transition. ## Three pieces that must all be there A working fade or slide needs three things at once: 1. **A view that is really inserted and removed.** The usual form is a conditional: `if showBanner { BannerView() }`. When `showBanner` becomes `true`, SwiftUI inserts the view; when it becomes `false`, SwiftUI removes it. 2. **A transition on that conditional view.** Attach `.transition(.opacity)`, `.transition(.move(edge: .top))`, `.transition(.scale)` or another built-in value to the view inside the `if`, not to some unrelated sibling. 3. **An animated state change.** Flip the Boolean inside `withAnimation { showBanner.toggle() }`, or attach `animation(_:value:)` to a container that is on screen in both states, such as the enclosing `VStack`. Without an animation, SwiftUI still applies the change, but the view simply pops in and out. If any one of the three is missing, the transition looks broken even though every line compiles. ## The built-in transitions SwiftUI ships a small set of ready-made transitions. Since iOS 17 they are values of concrete types conforming to the `Transition` protocol; the older type-erased `AnyTransition` offers the same names and still works. | Transition | What the inserted view does | |---|---| | `.opacity` | Fades from transparent to opaque, and back on removal | | `.move(edge:)` | Moves in from the given edge and out to it | | `.slide` | Slides in from one side and out the other | | `.scale` / `.scale(_:anchor:)` | Grows from a smaller scale, shrinking on removal | | `.offset(x:y:)` | Moves in from an offset you choose | | `.blurReplace` | Blurs and fades while it is replaced (iOS 17) | | `.identity` | No visual change at all | ## Combining and placing the modifier - **Combine two effects** with `combined(with:)`: `.move(edge: .top).combined(with: .opacity)` slides and fades at the same time, on both insertion and removal. - **Place `transition(_:)` on the conditional view**, the one the `if` creates. A transition on the parent stack describes how the *stack* enters and leaves, which is not what changed. - **Put the animation where it can see both states.** `withAnimation` wraps the state change itself, so it works from a button action. `animation(_:value:)` belongs on a container that exists before and after the change. - **Use different effects for entering and leaving** with an asymmetric transition, for example a toast that moves in from the top but fades out; that variant is the next step after the basics. ## A worked example A "Saved" banner that drops in from the top and fades, toggled by a button: ```swift struct SavedBanner: View { @State private var showBanner = false var body: some View { VStack { if showBanner { Text("Saved") .padding() .background(.green, in: .capsule) .transition(.move(edge: .top).combined(with: .opacity)) } Spacer() Button("Save") { withAnimation { showBanner.toggle() } } } } } ``` Tapping the button changes `showBanner` inside an animated transaction. On insertion the banner starts above its slot and transparent, then animates into place; on removal it runs the same effect in reverse. Swap `withAnimation` for `withAnimation(.snappy)` to change the timing; the transition decides *what* changes, the animation decides *how fast and with which curve*. ## Mistakes to avoid - **Hiding with `opacity(0)` and expecting a transition.** The view is still in the hierarchy, so only the opacity value animates and the transition is never consulted. - **Changing state without any animation.** The view appears and disappears instantly; the transition has no animation to ride on. - **Attaching the transition to the wrong view.** A transition on the `VStack` does nothing for a child that comes and goes. - **Reaching for the deprecated value-less `animation(_:)`.** It has been deprecated since iOS 15 in favour of `withAnimation` or `animation(_:value:)`. - **Using a transition to animate a value inside a view that stays**, such as a counter's digits. That is a content change inside one view, animated by other tools, not an insertion. Remember the one-line rule: a transition is how a view arrives and departs, so give SwiftUI an arrival or a departure, and make the change animated.

  • Why does the banner pop in instantly if you remove withAnimation but keep the transition?
    A transition only describes the starting and ending look of an inserted or removed view; the animation in the current transaction moves it between them. With no animation, SwiftUI applies the insertion immediately, so the view appears in its final state. Wrap the change in `withAnimation`, or add `animation(_:value:)` on a container present in both states.
  • What does combined(with:) do, and how is it different from using two transition modifiers?
    `combined(with:)` builds one transition that applies both effects together, such as `.move(edge: .top).combined(with: .opacity)`, so the view slides and fades on both insertion and removal. It is the supported way to merge effects; when entering and leaving should look different, use an asymmetric transition rather than stacking modifiers.

  • Adding transition(_:) alone makes the view animate in, no withAnimation needed.
  • Setting opacity to zero on a view runs its removal transition.
  • The transition modifier belongs on the parent stack, not on the conditional view.
  • The value-less animation(_:) modifier is the current way to animate appearance.
  • A transition plays whenever any property of the view changes.
open as a page

In SwiftUI, why does transition(_:) play only on insertion or removal, and how do you make a toast slide in but fade out?

level: middleimportance: must knowfreq 62%

basics

~20 s

A transition describes how a view enters or leaves the hierarchy, so a view that only changes values never uses it. Insert the toast with an if in an animated change and give it .asymmetric(insertion: .move(edge: .top), removal: .opacity).

open as a page

In SwiftUI, what is the difference between animation(_:value:) and withAnimation, and which views animate with each?

level: middleimportance: must knowfreq 75%

basics

~10 s

animation(_:value:) is a modifier that animates one view's subtree only when a watched Equatable value changes; withAnimation wraps a state mutation so every view whose rendering that mutation changes animates.

open as a page

A SwiftUI custom ProgressRing Shape with a stored progress property jumps to its new value even inside withAnimation; why, and how do you fix it?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Shape conforms to Animatable, but without an animatableData implementation it falls back to EmptyAnimatableData, so SwiftUI has nothing to interpolate and draws the end state. Expose progress through animatableData, or build the ring from Circle().trim(from:to:).

open as a page

In SwiftUI, how do you make a loading indicator cycle through several looks with phaseAnimator, and what does adding a trigger change?

level: juniorimportance: should knowfreq 45%

basics

~20 s

Apply phaseAnimator(_:content:animation:) (iOS 17) with a sequence of Equatable phases; SwiftUI animates each phase into the next and loops while the view is shown. With a trigger, it waits on the first phase and runs one pass per change.

open as a page

In SwiftUI, how do you animate a state change with a spring, and how do the smooth, snappy and bouncy presets differ?

level: juniorimportance: should knowfreq 60%

basics

~10 s

Pass a spring Animation such as .bouncy or .spring(duration: 0.4, bounce: 0.3) to withAnimation or animation(_:value:); .smooth has no bounce, .snappy a little and .bouncy the most, all with a 0.5-second default duration.

open as a page

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

level: middleimportance: should knowfreq 30%

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.

open as a page

On iOS 18 and later, how do you make a SwiftUI NavigationStack push zoom out of the tapped grid thumbnail?

level: middleimportance: should knowfreq 40%

basics

~10 s

Mark the thumbnail with matchedTransitionSource(id:in:) and give the destination's root view navigationTransition(.zoom(sourceID:in:)) with the same id and the same @Namespace. Both APIs arrived in iOS 18, and zoom is unavailable on macOS.

open as a page

In SwiftUI on iOS 17 and later, how do you run code when an animation finishes, and what do the completion criteria mean?

level: middleimportance: should knowfreq 40%

basics

~10 s

Use withAnimation(:completionCriteria::completion:), added in iOS 17: the closure runs exactly once, when the animations the change created are logically complete by default, or fully removed with .removed, or immediately if nothing animated.

open as a page

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%

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.

open as a page

In SwiftUI, a photo grid uses matchedGeometryEffect so a thumbnail grows into a full-screen photo, but the photo just pops in at full size; what usually causes that?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Usually the views are not one matched pair in one animated change: separate @Namespace instances or unequal ids, an unanimated change, two inserted sources, or a detail pushed or shown as a sheet instead of swapped in place.

open as a page

In SwiftUI, a tap should animate an expanding card's height, but the card jumps straight to its final size; what do you check, and in what order?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Check that the mutation runs synchronously inside withAnimation (not after an await), that any animation(_:value:) watches the value that changed and wraps the changing modifier, and that nothing below sets the transaction's animation to nil.

open as a page

In SwiftUI, a card's height animates through withAnimation, but an image inside it should snap to its new size; how do you exempt the image?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Apply transaction(:) to the image and set the transaction's animation to nil, so that subtree changes without animation while the card still animates; on iOS 17, transaction(value::) or transaction(_:body:) narrow the override further.

open as a page

In SwiftUI, how do you let a custom Shape animate two properties together, and what does the @Animatable macro change?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

animatableData holds one VectorArithmetic value, so two properties travel in an AnimatablePair (or AnimatableValues on iOS 26). The @Animatable macro, added in the iOS 26 SDK, synthesizes it from stored properties; non-animatable ones need @AnimatableIgnored.

open as a page

In SwiftUI, how do you build a custom transition with the Transition protocol, and what does TransitionPhase tell body(content:phase:)?

level: middleimportance: nice to knowfreq 25%

basics

~10 s

Conform a struct to Transition (iOS 17) and implement body(content:phase:), applying modifiers whose values depend on the phase: willAppear before insertion, identity while visible, didDisappear on removal. The animation interpolates between those values.

open as a page

In SwiftUI, how do you make a like counter's Text roll its digits when the count changes, and why can contentTransition seem to do nothing?

level: middleimportance: nice to knowfreq 30%

basics

~10 s

Apply .contentTransition(.numericText(value:)) to the Text and change the count inside an animation; content transitions only take effect when the update carries an Animation, so a plain count += 1 shows no effect.

open as a page