skip to content

In Core Animation, why does changing a standalone CAShapeLayer's strokeEnd animate by itself while a view's backing layer does not, and how does CATransaction control it?

level: middleimportance: should knowfreq 60%

answer

  1. a property change looks up an action
  2. the delegate is asked first
  3. the view declines outside a block
  4. a quarter of a second by default
  5. setDisableActions between begin and commit

basics

~20 s

Changing an animatable property on a standalone layer runs its implicit action, a 0.25-second animation by default. A view's backing layer asks the view, its delegate, which supplies none outside a UIView animation block. CATransaction sets duration, timing, completion, or disables actions.

solid answer

~40 s

When an animatable property changes, `CALayer` looks up an action with `action(forKey:)` using the property name. It asks the delegate's `action(for:forKey:)` first, then the layer's `actions` dictionary, then its `style`, then the class method `defaultAction(forKey:)`, which returns an animation for animatable properties. A layer you create yourself has no delegate, so the default action animates over the transaction's duration, 0.25 seconds unless changed. A view's backing layer has the view as its delegate, and UIKit animates that layer only inside a UIView animation block, so outside one the change applies at once. `CATransaction.begin()` and `commit()` scope `setAnimationDuration(_:)`, `setAnimationTimingFunction(_:)`, `setCompletionBlock(_:)` and `setDisableActions(_:)`; disabling actions is how you reset the ring to empty without a visible rewind. Properties such as a shape layer's `path` have no implicit animation at all.

code

swift · 20 lines
swift
import UIKit

@MainActor
func startInhale(ring: CAShapeLayer, seconds: CFTimeInterval) {
    // Reset the ring to empty at once: no implicit 0.25 s rewind.
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    ring.strokeEnd = 0
    CATransaction.commit()

    // Fill it over the whole inhale with the implicit strokeEnd action.
    CATransaction.begin()
    CATransaction.setAnimationDuration(seconds)
    CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: .easeInEaseOut))
    CATransaction.setCompletionBlock {
        print("inhale finished")
    }
    ring.strokeEnd = 1
    CATransaction.commit()
}

go deeper

for a junior

Recall that standalone layers animate property changes by themselves for a quarter of a second, and that CATransaction can turn that off.

for a middle

Explain the action lookup order, with the delegate asked first, and use it to say why the view's own layer animates only inside a UIView animation block.

for a senior

Show the working patterns: resetting without a rewind, a completion block set before the changes, NSNull in the actions dictionary, and explicit animations for path.

for a principal

Decide where a component's motion is declared, in one transaction helper or per-layer actions, so implicit animations stay predictable across a team's screens.

## Actions: what runs when a layer property changes In Core Animation, an **action** is an object conforming to the `CAAction` protocol that the layer runs when something happens to it, most often when an animatable property changes. A `CAAnimation` is a `CAAction`: running it adds the animation to the layer. When code assigns `ring.strokeEnd = 0.4`, the layer calls `action(forKey: "strokeEnd")`, and if it gets an animation back, the change from the old value to the new one is animated. This is an **implicit animation**: you changed a value and Core Animation supplied the motion. Property names are not the only events: a layer also looks up actions for `onOrderIn`, when it becomes visible, and `onOrderOut`, when it stops being visible. ## The lookup order `action(forKey:)` searches in a fixed order and stops at the first non-nil answer: 1. The **delegate's** `action(for:forKey:)`, if the delegate implements it. Returning `NSNull()` here explicitly stops the search. 2. The layer's **`actions`** dictionary. 3. Any `actions` dictionaries in the layer's **`style`** hierarchy. 4. The class method **`defaultAction(forKey:)`**, which returns a suitable animation for animatable properties and `nil` otherwise. If the result is `NSNull`, it is converted to `nil`, and nothing animates. ## Why a view's backing layer stays still A standalone `CAShapeLayer` you add with `addSublayer(_:)` has no delegate, so step 4 answers and the change animates. A view's backing layer is different: **the view is its delegate**, so step 1 answers first. UIKit's answer depends on context. Inside a UIView animation block, such as `UIView.animate(withDuration:animations:)` or a `UIViewPropertyAnimator`, the view supplies an animation that matches the block's timing. Outside one it supplies no action, so setting `view.layer.opacity` or `view.layer.cornerRadius` takes effect on the next frame. That is why the same assignment animates on a sublayer and not on the view's own layer. The working rule follows: animate a view's own layer inside a UIView animation block or with an explicit `CABasicAnimation`, and expect standalone sublayers to animate every change unless you turn their actions off. ## Transactions: implicit and explicit Every change to the layer tree belongs to a **`CATransaction`**, the unit in which changes are batched into the render tree. - An **implicit transaction** is created automatically when a thread modifies the layer tree with no transaction open, and it is committed when that thread's run loop next iterates. - An **explicit transaction** runs from `CATransaction.begin()` to `CATransaction.commit()`; transactions nest. - On a thread with no run loop, or one that is blocked, an explicit transaction may be needed for the change to reach the screen in time. ## The CATransaction properties Each property is per thread and scoped to the innermost transaction that set it: | Call | Default | Effect on implicit animations | |---|---|---| | `setAnimationDuration(_:)` | 0.25 s | length of every implicit animation in the transaction | | `setAnimationTimingFunction(_:)` | `nil` | when set, becomes the `timingFunction` of animations added in the transaction | | `setDisableActions(_:)` | `false` | `true` skips the action lookup, so changes apply with no animation | | `setCompletionBlock(_:)` | `nil` | runs on the main thread once the transaction's animations have finished or been removed | `setDisableActions(true)` affects only the action lookup. An animation you add explicitly with `add(_:forKey:)` still runs. ## Practical patterns - **Reset without a rewind.** Between breaths, set `strokeEnd = 0` inside a transaction with actions disabled; otherwise the ring visibly drains over 0.25 seconds before the next inhale. - **Lengthen an implicit animation.** Wrap the change in a transaction with `setAnimationDuration(4)` and an ease-in-ease-out timing function to fill the ring over a whole inhale without building a `CABasicAnimation`. - **Know when completion fires.** Set the completion block *before* the property changes; it waits only for animations added after it was set, and fires immediately if none are added before the commit. - **Silence one property for good.** Put `NSNull()` in the layer's `actions` dictionary under that key, for example `["position": NSNull()]`, and only that property stops animating implicitly. - **Some properties never animate implicitly.** Apple's documentation says `path` on `CAShapeLayer` and `shadowPath` on `CALayer`, like all `CGPath` properties, have no implicit animation; animate them with an explicit `CABasicAnimation`. The interview answer to give: implicit animation is an action lookup on property change, the view's delegate role explains the difference, and `CATransaction` is where you set its duration, timing, completion or turn it off.

  • When does a CATransaction completion block run, and why does the order of calls matter?
    It runs on the main thread once every animation added after the block was set, within that transaction group, has finished or been removed. If no animation is added before the commit, it runs immediately. So set it before the property changes, or it waits for nothing.
  • How do you stop one property of a standalone layer from ever animating implicitly?
    Put `NSNull()` under that key in the layer's `actions` dictionary, for example `layer.actions = ["position": NSNull()]`. The lookup finds a non-nil entry and stops, then treats `NSNull` as no action, so position changes apply at once while other properties still animate.
  • Why can a layer change made on a background thread appear late?
    With no open transaction, the change joins an implicit transaction that commits when that thread's run loop next iterates. A thread without a running run loop may not commit it promptly, so wrap such changes in an explicit `begin()` and `commit()`, or make them on the main thread.

  • A view's backing layer animates implicitly just like a standalone CALayer.
  • setDisableActions(true) also cancels explicit animations added with add(_:forKey:).
  • The default duration of an implicit layer animation is one second.
  • Changing a CAShapeLayer's path animates implicitly, just like changing strokeEnd.
  • A completion block set after the property changes still waits for their animations.