skip to content

In Core Animation, taps on the visible edge of a breathing app's bubble layer miss while it shrinks on an exhale; why, and how do you hit-test what is on screen?

level: seniorimportance: should knowfreq 50%

answer

  1. where it is versus where it will be
  2. the model already holds the end
  3. a copy as of this transaction
  4. presentation() then hitTest(_:)
  5. a point in the superlayer's space

basics

~20 s

Hit testing a layer reads the model layer, which already holds the animation's end values, while the screen shows the presentation layer. Call presentation() on the moving layer and hit-test or read its frame there, with the touch converted into the superlayer's coordinates.

solid answer

~50 s

Core Animation keeps two versions of each layer. The model layer holds the values you set, so with the end value set before animating, the bubble's model `position` or `transform` is already where the animation is heading. `presentation()` returns a copy that approximates what is on screen: the properties as of the start of the current transaction with active animations applied, or `nil` if the layer has never been committed. `hitTest(_:)` called on the model therefore tests where the bubble will be, not where the user sees it. Calling `hitTest(_:)` on `bubble.presentation()` queries the presentation tree instead, and its point must be in the superlayer's coordinate space. For a view moved with `UIView.animate`, UIKit also ignores touches during the animation unless you pass `.allowUserInteraction`, and its hit testing follows the view's model `frame`, so test the presentation frame yourself.

code

swift · 25 lines
swift
import UIKit

final class BreathingViewController: UIViewController {
    let bubble = CALayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        bubble.frame = CGRect(x: 40, y: 200, width: 120, height: 120)
        bubble.cornerRadius = 60
        bubble.backgroundColor = UIColor.systemTeal.cgColor
        view.layer.addSublayer(bubble)
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))))
    }

    @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
        // hitTest(_:) takes a point in the superlayer's coordinate space: view.layer here.
        let point = gesture.location(in: view)
        let onScreen = bubble.presentation() ?? bubble
        if onScreen.hitTest(point) != nil {
            pauseExercise()
        }
    }

    private func pauseExercise() {}
}

go deeper

for a junior

Recall that during an animation the layer object reports the end values, while presentation() reports what is currently displayed.

for a middle

Explain what the presentation copy contains, that it can be nil and is read-only, and which coordinate space hitTest(_:) expects.

for a senior

Diagnose the missed tap from first principles and fix it with a presentation-based hit test, covering UIKit's allowUserInteraction and model-frame hit testing for animated views.

for a principal

Decide when interactive animated elements should be views with gesture handling and when bare layers, given who owns hit testing and how often the team gets it wrong.

## Model tree, presentation tree Core Animation maintains a **model layer tree**, the `CALayer` objects your code creates and changes, and a **presentation tree** that reflects what is being displayed while animations run. They differ only while an animation is in flight, but that is exactly when users tap moving things. In the breathing app, the centre bubble swells to a 1.3 scale on each inhale and shrinks back to its resting size over four seconds on each exhale, and the user can tap it to pause the exercise. ## What presentation() returns `presentation()` on a layer returns a separate object with these properties: - It is a **copy** of the layer with all properties as they were at the start of the current transaction, **with active animations applied**: a close approximation of what is on screen. - It returns **`nil`** if the layer has not yet been committed, for example in the same run-loop turn that created it. - Its `sublayers`, `mask` and `superlayer` return presentation versions, and read-only methods such as `hitTest(_:)` query the presentation tree. - **Modifying it is undefined.** It is a snapshot for reading, not a handle on the animation. - Calling `model()` on it returns the underlying model layer, but only while the transaction that produced it is still current. ## Why the tap misses 1. The correct animation pattern sets the model to the end value first, so at the start of the exhale the bubble's model `transform` is already back to the resting size. 2. The animation then shows the bubble shrinking from the 1.3 scale. 3. A tap lands near the edge the user sees, which is still well outside the resting size. 4. `bubble.hitTest(point)` tests the model geometry, so that tap falls outside the smaller model shape and misses. During an inhale the error flips: taps just outside the visible bubble, inside the larger model shape, register as hits. The same mismatch appears with `position` animations. A layer sliding in from the left reports its final `frame` from the first frame of the slide. ## Hit-testing what the user sees | Approach | Tests against | Suitable when | |---|---|---| | `bubble.hitTest(point)` | model geometry, the end values | the layer is at rest | | `bubble.presentation()?.hitTest(point)` | the displayed geometry | the layer is animating | | `bubble.presentation()?.frame.contains(point)` | the displayed frame only | a quick rectangular test | `hitTest(_:)` expects the point in the **coordinate system of the receiver's superlayer**. When the bubble is a sublayer of `view.layer`, `gesture.location(in: view)` already is in that space; for a deeper layer, convert with `convert(_:from:)` first. Fall back to the model layer when `presentation()` returns `nil`. Because the copy reflects the current transaction, fetch it inside the tap handler instead of caching it in a property. ## Views animated by UIKit A `UIView` animated with `UIView.animate(withDuration:delay:options:animations:completion:)` has the same split: its `frame` and `center` report the end values at once, and its layer's `presentation()` shows the motion. UIKit adds two behaviours on top: - Touches are **disabled** for views being animated unless the options include **`.allowUserInteraction`**. - UIKit's own hit testing follows the views' model geometry, so a button sliding across the screen responds where it is going, not where it is drawn. A container can override `hitTest(_:with:)` and test the child's `layer.presentation()?.frame` to fix that. ## Other reasons to read the presentation layer - **Interrupting an animation.** When the user pauses mid-inhale, start the next animation's `fromValue` from the presentation value, not from the model's end value, or the bubble jumps. - **Freezing in place.** To stop at the current size, copy the presentation value into the model inside a transaction with actions disabled, then remove the animation. - **Debugging.** Logging `bubble.transform` next to `bubble.presentation()?.transform` during an exhale shows the two trees diverging, the quickest way to show a reviewer why the tap misses. - **`.beginFromCurrentState`.** UIKit's option tells a new view animation to start from the current on-screen value rather than the initial one, which is the view-level form of the same idea. What an interviewer listens for: the candidate says which tree each API reads, knows that `presentation()` is a read-only copy that can be `nil`, and gets the coordinate space of `hitTest(_:)` right.

  • Why start an interrupted animation's fromValue from presentation() rather than the model?
    When the user pauses mid-inhale, the model already holds the old end value. Starting the next animation there makes the bubble jump to the end and back. Reading the value from `presentation()` gives the size on screen, so the new animation continues from where the user's eye is.
  • Can you redirect the running animation by setting properties on the presentation layer?
    No. Modifying the layer `presentation()` returns is undefined: it is a snapshot copy for reading. To change course, set the model value, with actions disabled if needed, and add a new animation that starts from the presentation value.

  • presentation() returns the layer itself, since model and display are one object.
  • Calling hitTest(_:) on the model layer follows the animation as the layer moves.
  • Writing to the presentation layer is a quick way to nudge a running animation.
  • presentation() always returns a value, even for a layer that was never committed.
  • A view being moved by UIView.animate receives touches by default.