In Core Animation, why does a breathing ring's CABasicAnimation on strokeEnd snap back to empty when it ends, and what are the two fixes?
answer
- two copies of every property
- the animation never writes the model
- removed when its duration ends
- isRemovedOnCompletion plus fillMode
- set the model value first
basics
~20 sAn explicit CABasicAnimation changes only the displayed value, not the layer's model strokeEnd, and is removed when it ends, so the ring jumps back. Set the model value before adding the animation, or keep the animation with isRemovedOnCompletion false and fillMode forwards.
solid answer
~40 sAdding `CABasicAnimation(keyPath: "strokeEnd")` with `add(_:forKey:)` hands a copy of the animation to the render tree. It drives what the presentation layer shows, but the model layer's `strokeEnd` keeps whatever you last assigned, here `0`. Because `isRemovedOnCompletion` defaults to `true` and `fillMode` to `removed`, the animation leaves when its duration passes and the ring shows the model value again. The preferred fix is to set `strokeEnd = 1` on the model, inside `CATransaction.setDisableActions(true)` for a standalone layer so no implicit animation competes, and then add the animation from the old value. The other fix, `isRemovedOnCompletion = false` with `fillMode = .forwards`, freezes the final frame but leaves the model wrong and the animation attached, which misleads any later read, hit test or animation.
code
swift · 19 linesimport UIKit
@MainActor
func fillBreathRing(_ ring: CAShapeLayer, duration: CFTimeInterval) {
let fill = CABasicAnimation(keyPath: "strokeEnd")
fill.fromValue = ring.presentation()?.strokeEnd ?? ring.strokeEnd
fill.toValue = 1.0
fill.duration = duration
fill.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
// Move the model layer to the final value, with no implicit animation.
CATransaction.begin()
CATransaction.setDisableActions(true)
ring.strokeEnd = 1.0
CATransaction.commit()
// The explicit animation now only draws the journey to that value.
ring.add(fill, forKey: "breathFill")
}go deeper
Recall that an explicit layer animation changes only what is displayed, and that setting the model value is what makes the end state stick.
Walk through the model and presentation values over the animation's life, name both defaults, isRemovedOnCompletion true and fillMode removed, and give both fixes.
Argue for updating the model with actions disabled, and show what the fill-mode fix breaks: later reads, the next animation's start, hit tests and a retained delegate.
Set a team rule that layer animations always move the model first, so review can reject the fill-mode shortcut except for throwaway layers removed at the end.
## Two values for one property Core Animation keeps two parallel trees of layers. The **model layer** is the object your code holds: when you assign `ring.strokeEnd = 1`, that is the value stored. The **presentation layer**, returned by `presentation()`, approximates what is on screen right now, with every running animation applied. Most of the time the two agree. An explicit animation is precisely the period when they do not. | | Model layer | Presentation layer | |---|---|---| | What it holds | the values your code last set | the values currently displayed | | Changed by `add(_:forKey:)` | no | yes, for the animation's duration | | Read through | the layer itself, e.g. `ring.strokeEnd` | `ring.presentation()?.strokeEnd` | | You may assign to it | yes | no, the effect is undefined | ## What an explicit animation actually changes A **`CABasicAnimation`** interpolates one key path between `fromValue` and `toValue`. When you call `layer.add(_:forKey:)`, the render tree **copies** the animation object; editing your object afterwards has no effect, and adding another animation under the same key replaces the first. While it runs, the animation overrides the displayed value of `strokeEnd`. It never writes to the model. Two timing properties decide what happens at the end: - **`isRemovedOnCompletion`** defaults to `true`: once the active duration has passed, the animation is removed from the layer. - **`fillMode`** defaults to `.removed`; `.forwards` holds the last frame after the active duration, `.backwards` applies the first frame before a delayed start, and `.both` does both. ## Why the ring snaps back In the breathing app, the ring is a `CAShapeLayer` whose `strokeEnd` starts at `0`. The broken code adds a four-second animation from `0` to `1` and stops there. 1. The animation is added; the presentation layer starts drawing `strokeEnd` rising from `0`. 2. The model's `strokeEnd` stays `0` the whole time. 3. At four seconds the animation is removed, because removal on completion is the default. 4. The presentation layer has nothing overriding the model any more, so it shows `0`: the ring empties in a single frame. The mirror image happens with a delayed start. Before an animation's `beginTime` arrives, the layer shows the model value, unless `fillMode` is `.backwards` or `.both`, which apply the first frame early. ## Fix 1: update the model, then animate Set the model to the end value and let the animation describe only the journey there: - Assign `ring.strokeEnd = 1` inside a transaction with `CATransaction.setDisableActions(true)`. A standalone layer would otherwise start its own 0.25-second implicit animation for that change. - Build the animation with `fromValue` read from `presentation()` (or the old model value) and `toValue` of `1`. - Add it; when it is removed at the end, the model already shows a full ring, so nothing jumps. Reading `fromValue` from `presentation()` matters when a new breath begins before the previous animation has finished: the ring continues from what is on screen instead of jumping to the model's value first. This keeps the model truthful. Later reads of `strokeEnd`, hit tests against the model and the next animation's starting point are all correct. ## Fix 2: keep the animation on the layer Setting `isRemovedOnCompletion = false` together with `fillMode = .forwards` leaves the finished animation attached, holding its last frame. It looks right, and it is sometimes used deliberately for a throwaway layer. Its costs are real: - The model still says `0`, so code that reads `strokeEnd` or animates from it starts from the wrong value. - The animation stays in the layer's `animationKeys()` until you remove it. - `fillMode = .forwards` on its own does nothing visible at the end; removal still happens, because `isRemovedOnCompletion` is still `true`. - The animation's `delegate` is retained for the animation's lifetime, so a delegate on an animation that is never removed stays alive with it. ## The same rule for keyframes and springs Every `CAAnimation` subclass behaves this way. A **`CAKeyframeAnimation`** with `values` and `keyTimes` that swells the centre circle on each inhale animates the presentation only; if its last value differs from the model's `transform`, it jumps back too. A **`CASpringAnimation`** (iOS 9), which adds `mass`, `stiffness`, `damping` and `initialVelocity`, is a `CABasicAnimation` subclass and follows the same rule. UIKit's `UIView.animate(withDuration:animations:)` avoids the problem by design: the closure sets the model values and UIKit builds the layer animations from the old values to the new ones.
- Does the same snap-back happen with a CAKeyframeAnimation that swells the centre circle on each inhale?Yes. Every `CAAnimation` animates only the presentation and is removed on completion by default. A swell whose `values` start and end at the identity transform looks fine because the model already holds that end value; one that ends at a 1.3 scale jumps back unless the model `transform` is set to that scale too.
- Why does changing the animation object after add(_:forKey:) have no effect?The render tree copies the animation when it is added, so later edits to your object never reach it. To change a running animation, build a new one and add it; adding under the same key replaces the old one, because a layer keeps only one animation per key.
- A technique card rotated about its y axis looks flat; what does m34 change?Without perspective, a y-axis rotation is drawn as a flat projection, so the card just narrows. Setting a `CATransform3D`'s `m34` to a small negative value such as `-1/500` before rotating adds perspective, so the near edge draws larger than the far edge. Setting it in the superlayer's `sublayerTransform` gives sibling cards one shared vanishing point.
A price tag and a sale banner: the banner covers the tag while the sale runs, but when it comes down the tag is what shoppers see, so a lasting price means changing the tag itself, not leaving the banner up for good.
- An explicit animation writes toValue into the layer's property when it finishes.
- isRemovedOnCompletion false with fillMode forwards is the standard fix and has no side effects.
- fillMode forwards alone keeps the end state even while removal on completion stays on.
- Reading layer.strokeEnd during an animation returns the value currently on screen.
- A CAAnimation's delegate is held weakly, so it can never keep a controller alive.