In SwiftUI on iOS 17 and later, how do you run code when an animation finishes, and what do the completion criteria mean?
answer
- no more timers set to the duration
- a trailing completion closure
- logically done versus removed
- called exactly once
- completions on a transaction
basics
~10 sUse 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.
solid answer
~40 sSince iOS 17, `withAnimation(.bouncy) { scale = 1.3 } completion: { ... }` runs the completion when the animations created by that change finish. The `completionCriteria` parameter decides what "finish" means: the default, `.logicallyComplete`, fires when the animation has logically completed even if it is still in its long tail, which matters for springs; `.removed` waits until the animation is entirely finished and removed. The documentation guarantees the callback fires exactly once, and immediately after the body if the change created no animations. For implicit animations, `Transaction.addAnimationCompletion(criteria:_:)` attaches the same kind of completion to a transaction. This replaces the old habit of scheduling `DispatchQueue.main.asyncAfter` with a guessed duration.
code
swift · 19 linesstruct PoppingHeart: View {
@State private var isLiked = false
@State private var heartScale = 1.0
var body: some View {
Image(systemName: isLiked ? "heart.fill" : "heart")
.font(.largeTitle)
.scaleEffect(heartScale)
.onTapGesture {
isLiked.toggle()
withAnimation(.bouncy) {
heartScale = 1.3
} completion: {
// Runs once, when the pop is logically complete.
withAnimation(.smooth) { heartScale = 1.0 }
}
}
}
}go deeper
Recall that since iOS 17 withAnimation can take a completion closure, so you do not need a timer.
Explain logicallyComplete versus removed, the exactly-once guarantee and the immediate call when nothing animates.
Choose the criterion per use, attach completions through Transaction.addAnimationCompletion for implicit animations, and know when a chain should become a phase or keyframe animator.
Be ready to justify replacing timer-based chaining across a codebase and to plan the iOS 16 fallback if the deployment target still requires it.
## The problem completions solve Many interactions need to do something **after** an animation: chain a second movement, remove a temporary badge, start a haptic or announce a result. Before iOS 17 SwiftUI had no completion API for state-driven animations, so code commonly scheduled `DispatchQueue.main.asyncAfter` with the animation's duration. That guess breaks easily: - A spring's `duration` is passed to it as its response, not a hard end time, so the motion can still be settling. - `speed(_:)` and `delay(_:)` change the real timing without changing the guessed number. - If the change produced no animation, the timer still waits for nothing. ## `withAnimation` with a completion iOS 17 added `withAnimation(_:completionCriteria:_:completion:)`. Its documentation says it sets the animation on the current transaction "as well as calling `Transaction/addAnimationCompletion` with the specified completion", and gives two guarantees: - The completion **"will always be fired exactly one time."** - **"If no animations are created by the changes in `body`, then the callback will be called immediately after `body`."** ```swift withAnimation(.bouncy) { heartScale = 1.3 } completion: { withAnimation(.smooth) { heartScale = 1.0 } } ``` The like button's heart grows with a bouncy spring, and only when that animation completes does it ease back to its resting size. The completion is a plain closure, so it can start the next animation, update state or trigger feedback. ## What "complete" means: the two criteria `AnimationCompletionCriteria` has two values: | Criterion | Documentation | When to use | |---|---|---| | `.logicallyComplete` (default) | "The animation has logically completed, but may still be in its long tail." | Chaining the next step so motion flows on | | `.removed` | "The entire animation is finished and will now be removed." | Work that needs the motion fully at rest | The difference is clearest with springs. A spring approaches its target quickly and then spends time in small, barely visible movements. Waiting for `.removed` makes a chained step feel late; `.logicallyComplete` lets the next step start while the tail finishes. Use `.removed` when something genuinely depends on the animation being entirely over. Choosing the criterion in practice: - **Chaining the next movement:** `.logicallyComplete`. The eye already reads the motion as done, and the next animation starts without a visible pause. - **Re-enabling input that was blocked during the motion:** usually `.logicallyComplete`, so the interface does not feel unresponsive during a tail nobody can see. - **Work that must not overlap any residual motion:** `.removed`, which waits until the animation is gone entirely. An animation can also be told when to report logical completion: iOS 17's `Animation.logicallyComplete(after:)` "causes the animation to report logical completion after the specified duration, if it has not already logically completed." ## Completions on a transaction Completions are not limited to `withAnimation`. `Transaction.addAnimationCompletion(criteria:_:)`, also iOS 17, "adds a completion to run when the animations created with this transaction are all complete". That makes completions available wherever you hold a transaction: 1. Inside `withTransaction`, by building a `Transaction`, setting its `animation` and adding a completion. 2. Inside a `transaction(_:)` or `transaction(value:_:)` modifier, which receives the transaction as an `inout` parameter. 3. In a custom control that receives a transaction and wants to report when its own motion ends. ## A completion versus a multi-step animation A completion chains a few discrete steps around one state change. When an effect is really a sequence of phases or a timeline of keyframes, such as a mascot that hops, lands and squashes, SwiftUI's phase and keyframe animators describe it declaratively; those belong with custom and keyframe animation. Two or three chained completions are fine; a pyramid of them is a sign the effect wants a phase or keyframe animator. ## Pitfalls - **Expecting a delay when nothing animates.** If the body changes no animatable value, the completion runs immediately after it. - **Using `.removed` for chaining.** It waits for the long tail, which feels sluggish with springs. - **Back-deployment.** These APIs need iOS 17; an app that still deploys to iOS 16 must guard them with `#available`. - **Capturing state in the completion.** The closure runs later; read current state there rather than values captured before the animation started, if they may have changed.
- What happens to the completion if the closure passed to withAnimation changes nothing that animates?It still runs, exactly once, immediately after the body. Apple's documentation states that the callback always fires one time and that, if no animations are created by the changes in the body, it is called right after the body. Code in the completion therefore cannot assume that time has passed.
- How do you get a completion for an animation that a transaction modifier applies, rather than withAnimation?Use `Transaction.addAnimationCompletion(criteria:_:)`, added in iOS 17. Any code holding the transaction, such as a `transaction(_:)` modifier closure or a transaction built for `withTransaction`, can add a completion that runs when the animations created with that transaction are all complete.
logicallyComplete is a runner crossing the finish line, when the next race can be called; removed is the same runner finishing the cool-down jog and leaving the track.
- SwiftUI has no animation completion, so a timer set to the duration is the only option.
- The default criterion waits until the spring has completely stopped moving.
- If nothing animates, the completion closure never runs.
- The completion runs once per animated view the change touched.
- withAnimation's completion is available on every iOS version SwiftUI supports.