skip to content

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%

answer

  1. one body requirement
  2. willAppear, identity, didDisappear
  3. isIdentity drives modifier values
  4. no if or id inside

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.

solid answer

~40 s

Since iOS 17 a custom transition is a type conforming to `Transition`. Its one requirement, `body(content:phase:)`, receives the transitioned view as `content` and a `TransitionPhase`: `.willAppear` as an inserted view starts, `.identity` while it is visible, `.didDisappear` as a removed view leaves. Return the content with modifiers driven by the phase, for example `.opacity(phase.isIdentity ? 1 : 0)`. Apple's documentation adds three rules: make no visual change in identity, apply an animatable change in the other phases or the transition is a no-op, and never use `.id`, `if` or `switch` on the content. Expose it with an `extension Transition where Self == MyTransition` so call sites write `.transition(.myTransition)`; before iOS 17, `AnyTransition.modifier(active:identity:)` filled this role.

code

swift · 19 lines
swift
struct BlurFadeTransition: Transition {
    var radius: CGFloat = 12

    func body(content: Content, phase: TransitionPhase) -> some View {
        content
            .opacity(phase.isIdentity ? 1 : 0)
            .blur(radius: phase.isIdentity ? 0 : radius)
    }

    static var properties: TransitionProperties {
        TransitionProperties(hasMotion: false)
    }
}

extension Transition where Self == BlurFadeTransition {
    static var blurFade: BlurFadeTransition { BlurFadeTransition() }
}

// Usage: if showDetails { DetailsCard().transition(.blurFade) }

go deeper

for a junior

Recall that a custom transition is a type conforming to Transition with a body(content:phase:) method, and that the phase says whether the view is appearing, visible or disappearing.

for a middle

Explain the three phases and the documented rules: unchanged in identity, an animatable change otherwise, and no identity changes inside the body. Show the static-member extension for dot syntax.

for a senior

Spot a custom transition that resets state because it switches content inside the body, and rewrite it with phase-driven modifier values. Say when hasMotion matters.

for a principal

Judge whether a design system should publish a few named custom transitions as static members, so teams reuse vetted motion instead of hand-writing modifier pairs per screen.

## The Transition protocol Since iOS 17, SwiftUI's transitions are values of types that conform to the **`Transition`** protocol. The built-in ones (`OpacityTransition`, `MoveTransition`, `ScaleTransition`, `AsymmetricTransition` and the rest) are ordinary conforming types, and you can write your own the same way. The protocol is small: - **`body(content:phase:)`** is the one requirement you implement. It receives the view being transitioned as `content` and the current `TransitionPhase`, and returns that content with modifiers applied. The method is a view builder, just like a view's `body`. - **`Content`** is a type alias for `PlaceholderContentView<Self>`: a stand-in for whatever view the transition is attached to. You never create it; you only modify it. - **`properties`** is a static `TransitionProperties` value with a default. It currently carries one flag, `hasMotion`, and Apple's documentation says these properties can determine how a transition interacts with other features such as accessibility settings. - **Isolation**: the protocol is main-actor isolated. A conformance written in the type's own declaration inherits that isolation; one written in an extension is nonisolated by default. ## The three phases `TransitionPhase` is an enum that tells your body where in its life the view is: | Phase | When it applies | What your body should render | |---|---|---| | `.willAppear` | Just before an inserted view becomes visible | The "off" look the view animates in from | | `.identity` | While the view is on screen | The view unchanged | | `.didDisappear` | When a removed view finishes leaving | The "off" look the view animates out to | The documentation describes the sequence: an appearing view is first shown in `willAppear` and is immediately moved to `identity`; a removed view goes from `identity` to `didDisappear`. The animation in the current transaction interpolates the modifier values between those phases. Two helpers make bodies short: **`isIdentity`** is `true` only in the identity phase, and **`value`** gives a number for the phase that you can scale an offset or angle by. ## Writing one A transition that blurs and fades a view, without moving it: ```swift struct BlurFadeTransition: Transition { var radius: CGFloat = 12 func body(content: Content, phase: TransitionPhase) -> some View { content .opacity(phase.isIdentity ? 1 : 0) .blur(radius: phase.isIdentity ? 0 : radius) } static var properties: TransitionProperties { TransitionProperties(hasMotion: false) } } extension Transition where Self == BlurFadeTransition { static var blurFade: BlurFadeTransition { BlurFadeTransition() } } ``` The extension constrained to `Self == BlurFadeTransition` lets call sites write `.transition(.blurFade)`, exactly like the built-in names. Because this transition only blurs and fades, it reports `hasMotion: false`. For a transition that should look different on the way in and the way out, switch on the phase itself instead of `isIdentity`, for example rotating one way in `willAppear` and the other way in `didDisappear`. That is how Apple's own example of a rotating fade is written. ## Rules the documentation gives Apple's pages for `Transition` and `TransitionPhase` state three rules worth quoting in an interview: 1. **In the identity phase, make no visual change.** The identity-phase modifiers stay applied for as long as the view is visible, so anything you change there changes the view permanently. 2. **In the other phases, apply an animatable change.** If no animatable change is applied, the transition is a no-op. 3. **Do not change identity inside the body.** Transitions should not use `.id`, `if` or `switch` on the content, because doing so resets the state of the view they are applied to, wasting work and causing surprising behaviour as it appears and disappears. The third rule is the subtle one. `body` is a view builder, so an `if` compiles; it is still wrong, because it swaps the content for a new view mid-transition. Express every difference as a modifier value that changes with the phase. ## Composing and reusing - **Combine** a custom transition with another through `combined(with:)`: `.blurFade.combined(with: .scale)`. - **Use different transitions per direction** with `AsymmetricTransition(insertion:removal:)`. - **Give a transition its own animation** with its `animation(_:)` method. - **Apply** it like any other: `.transition(.blurFade)` on a view inside an `if`, with the change animated. ## Before iOS 17 The older route is still available: `AnyTransition.modifier(active:identity:)` takes two values of a `ViewModifier` type, one for the off state and one for the on state, and wraps them in a type-erased `AnyTransition`. It works on every release, but it needs a separate modifier type, cannot see the difference between appearing and disappearing, and erases the type. For apps whose deployment target is iOS 17 or later, the common baseline today, the `Transition` protocol is the simpler route. ## What to remember - Implement `body(content:phase:)` and let the phase drive modifier values. - Leave the view untouched in `identity`; make an animatable change in the other phases. - Never change identity in the body. - Describe whether the transition has motion through `properties`.

  • How would you make the custom transition rotate one way in and the other way out?
    Switch on the phase rather than reading `isIdentity`: return, say, 30 degrees for `.willAppear`, zero for `.identity` and minus 30 degrees for `.didDisappear`, and apply it with `rotationEffect`. The two non-identity phases are distinct cases, so one transition can look different in each direction without being asymmetric.
  • What did people write before the Transition protocol, and why prefer the protocol now?
    They used `AnyTransition.modifier(active:identity:)` with a custom `ViewModifier` for the off and on states. It still works, but it needs a separate modifier type, cannot tell appearing from disappearing, and is type-erased. With an iOS 17 deployment target, a `Transition` type is simpler and sees the phase directly.

  • The identity phase is a good place to add a subtle permanent effect.
  • An if inside body(content:phase:) is fine because the body is a view builder.
  • If no modifier changes between phases, SwiftUI falls back to a fade.
  • A custom transition must subclass AnyTransition to be used with transition(_:).
  • TransitionPhase has only two states, visible and hidden.