skip to content

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%

answer

  1. arriving versus changing
  2. same identity, only values animate
  3. if, ForEach or a new id
  4. asymmetric(insertion:removal:)

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).

solid answer

~40 s

SwiftUI animates two different things: value changes on a view that keeps its identity, and the insertion or removal of a view. `transition(_:)` only covers the second, so a visible toast whose text changes never replays it. Insertion and removal come from an `if` or `switch` branch, a `ForEach` element, or a new `id(_:)` value, and the change must be animated with `withAnimation` or with `animation(_:value:)` on a container present in both states. For different motion each way, use `.transition(.asymmetric(insertion: .move(edge: .top), removal: .opacity))`, or `AsymmetricTransition` with `Transition` values on iOS 17 and later. Add `.id(message)` if each new message should arrive as a new toast.

code

swift · 20 lines
swift
struct ToastDemo: View {
    @State private var toast: String?

    var body: some View {
        VStack {
            if let toast {
                Text(toast)
                    .padding()
                    .background(.thinMaterial, in: .capsule)
                    .transition(.asymmetric(insertion: .move(edge: .top),
                                            removal: .opacity))
                    .id(toast)
            }
            Spacer()
            Button("Copy link") { toast = "Link copied" }
            Button("Dismiss") { toast = nil }
        }
        .animation(.snappy, value: toast)
    }
}

go deeper

for a junior

Recall that a transition plays when a view appears or disappears, and that the change has to be animated. Know that asymmetric lets the way in differ from the way out.

for a middle

Explain the two kinds of animated change, identity kept versus inserted or removed, and list what causes insertion: if, switch, ForEach and a new id. Show where animation(_:value:) must sit.

for a senior

Diagnose a toast that does not replay on a new message and fix it with a new identity, and reason about interrupted transitions through the phase model rather than adding delays.

for a principal

Weigh where motion rules live in a codebase: a shared toast container that owns its transition and animation keeps every feature consistent and stops each screen reinventing insertion logic.

## Two kinds of change SwiftUI can animate SwiftUI animates the difference between two states of your interface. Between any two states, a given view has had one of two things happen to it, and SwiftUI animates each one differently: | What happened to the view | What SwiftUI animates | What you configure | |---|---|---| | It stayed, with the **same identity**, and some modifier values changed | The changed values themselves: opacity, offset, frame, color | The animation (`withAnimation`, `animation(_:value:)`) | | It was **inserted** or **removed** | The view's arrival or departure | The view's `transition(_:)` plus the animation | A **transition** belongs only to the second row. Apple describes the `Transition` protocol as "a description of view changes to apply when a view is added to and removed from the view hierarchy". When a toast stays on screen and only its text changes, it was neither added nor removed, so its transition is never used, however you animate the change. ## What counts as insertion or removal From the transition's point of view, a view comes and goes when its identity begins or ends. In practice that happens in a few ways: - **An `if` or `if let` branch** becomes true or false, so the view inside it is created or destroyed. - **A `switch` or `if`/`else`** moves from one branch to another: the old branch's view is removed and the new one inserted. - **A `ForEach` element** is added to or removed from its data. - **An `id(_:)` value changes.** The documentation for `id(_:)` says that when the value changes, the identity of the view is reset; to SwiftUI the old view is removed and a new one inserted. The full rules of structural and explicit identity are covered with view identity; here only the consequence matters: a new identity means a new insertion. That last point answers the common toast question. If a toast is visible and its message changes from "Copied" to "Saved", the `if let message` branch is still true, the same `Text` remains, and only its string changes. Adding `.id(message)` to the toast gives each message its own identity, so the old toast leaves with its removal transition and the new one arrives with its insertion transition. ## The change must be animated Insertion and removal alone are not enough. The transition supplies the before and after appearance; the **animation** in the current transaction carries the view between them. Two ways to supply it: - **`withAnimation`** around the state change, for example in a button action. - **`animation(_:value:)` on a container that exists in both states**, such as the `VStack` holding the `if`. A modifier attached to the toast itself exists only while the toast does, so it cannot observe both sides of the change. Without either, SwiftUI inserts and removes the view immediately. ## Asymmetric transitions for a toast A toast often wants different motion on the way in and the way out: it should slide down from the top so the eye follows it, then fade so it does not pull attention when it leaves. `AnyTransition.asymmetric(insertion:removal:)` takes one transition for each direction; since iOS 17 there is also the `AsymmetricTransition` type built from `Transition` values. ```swift struct ToastDemo: View { @State private var toast: String? var body: some View { VStack { if let toast { Text(toast) .padding() .background(.thinMaterial, in: .capsule) .transition(.asymmetric(insertion: .move(edge: .top), removal: .opacity)) .id(toast) } Spacer() Button("Copy link") { toast = "Link copied" } Button("Dismiss") { toast = nil } } .animation(.snappy, value: toast) } } ``` The animation sits on the `VStack`, which is present whether or not the toast is shown. Because of `.id(toast)`, changing the message also replays the transition. ## Interrupted transitions Users tap quickly, so a toast may be dismissed while it is still arriving. The `TransitionPhase` documentation describes what happens: a view appearing starts in the `willAppear` phase and moves to `identity`; a view being removed goes from `identity` to `didDisappear`. If it is removed while still transitioning in, its phase changes to `didDisappear`; if it is re-added while transitioning out, its phase changes back to `identity`. SwiftUI handles the reversal for you, as long as the transition is expressed through phase-driven, animatable modifiers. ## A checklist when a transition does not play 1. Is the view really inserted or removed, or does it stay with the same identity? 2. Is the transition attached to the view that comes and goes? 3. Is the state change animated, by `withAnimation` or by `animation(_:value:)` on a container present in both states? 4. Do insertion and removal need different effects? Use an asymmetric transition. 5. Should a new message count as a new view? Give it a new identity with `id(_:)`. In a ZStack, if a departing view disappears behind a sibling while it animates out, give it an explicit `zIndex(_:)` so the front-to-back order stays the one you intend.

  • What happens if the user dismisses the toast while it is still sliding in?
    Apple's `TransitionPhase` documentation says a view removed while it is still transitioning in changes its phase to `didDisappear`, and a view re-added while transitioning out goes back to `identity`. SwiftUI reverses the motion from wherever it is, so the toast fades out mid-flight instead of finishing its arrival first.
  • Why put animation(_:value:) on the VStack rather than on the toast?
    The toast exists only while it is shown, so a modifier attached to it is missing on one side of every insertion or removal. The enclosing `VStack` is present before and after the change, so its `animation(_:value:)` sees the value change and animates the transaction that inserts or removes the toast.
  • How would you make the toast leave by sliding up and fading together?
    Use a combined removal inside the asymmetric transition: `.asymmetric(insertion: .move(edge: .top), removal: .move(edge: .top).combined(with: .opacity))`. The insertion stays a plain move, while the removal applies both effects at once as the toast departs.

  • A transition replays whenever the toast's text changes, as long as it is animated.
  • Hiding the toast with opacity counts as removing it for its transition.
  • combined(with:) gives one effect on insertion and a different one on removal.
  • animation(_:value:) on the toast itself reliably animates its own insertion and removal.
  • Transitions cannot be interrupted, so a fast dismiss waits for the arrival to finish.