Hello! Welcome back to our module on Core UIKit Animations.
In our last lesson, we mastered composing animation sequences using UIView.animateKeyframes. This gave us precise control over multi-stage animations with clean, readable code. We also had a brief glimpse of the underlying Core Animation framework with CAKeyframeAnimation.
Today, we're diving fully into Core Animation. Our goal is to learn how to animate layer properties directly using CABasicAnimation. While UIView animations are convenient, understanding how to work directly with CALayer and explicit animation objects like CABasicAnimation is a hallmark of a professional iOS developer. It unlocks a new level of control, performance, and the ability to animate properties that UIView doesn't expose.
Recap: Views, Layers, and the Two-Layer System
As a refresher, every UIView is backed by a CALayer. The view manages user interaction and layout, while the layer handles the rendering and animation of the view's content on the screen. When we use UIView.animate, we are indirectly manipulating this underlying layer.
The most critical concept to grasp when working directly with Core Animation is that it maintains two parallel layer hierarchies:
- The Model Layer Tree: This is the "source of truth." Its properties reflect the actual state of your layer. When you set
myView.layer.opacity = 0.5, you are changing a property on the model layer. - The Presentation Layer Tree: This reflects what is currently visible on screen during an animation. It is temporary and read-only.
This separation is the source of a very common problem. When you add a CABasicAnimation to a layer, it only affects the presentation layer. Once the animation completes, the presentation layer is discarded, and the screen reverts to showing the model layer's values. This causes the infamous "snap-back" effect, where your view animates to a new state and then instantly jumps back to where it started.
The article "Animations Explained" from objc.io provides one of the clearest explanations of this two-layer system. While the code is in Objective-C, the concepts are fundamental and universal to Core Animation.
Please read the first two sections, "First Things First" and "A Basic Animation". Focus on understanding the distinction between the model layer tree and the presentation layer tree. Notice the description of the 'snap-back' effect when the model layer isn't updated.
The key takeaway is this: to make an animation "stick," you must update the model layer's properties to match the final state of your animation.
Anatomy of a CABasicAnimation
CABasicAnimation is a beautifully simple object. It animates a single layer property from a starting value to an ending value over a specified duration.
Here's a breakdown of its core components:
init(keyPath: String?): ThekeyPathis a string that identifies theCALayerproperty you want to animate. Examples include"opacity","position","transform.scale", or"cornerRadius".fromValue: The starting value of the property. If you leave this asnil, Core Animation uses the property's current value from the model layer.toValue: The ending value of the property.duration: The animation's duration in seconds.timingFunction: An object of typeCAMediaTimingFunctionthat defines the animation's pacing (e.g., ease-in, ease-out, linear). This is the Core Animation equivalent of the timing curves we used inUIView.animate.
Let's see how these pieces come together.

Building and Applying a CABasicAnimation
The following video provides an excellent, hands-on demonstration of creating a CABasicAnimation from scratch. It walks through building an animation, applying it to a layer, and correctly handling the final state to prevent the "snap-back" effect.
This tutorial from Code Pro will guide you through creating your first CABasicAnimation to animate a view's position.
Watch from 00:59 to 08:16. The first part (until 06:50) introduces Core Animation and the setup for a CABasicAnimation object, explaining properties like keyPath, fromValue, toValue, duration, and timingFunction. The second part (from 06:50 to 08:16) shows how to apply this animation to a layer and, crucially, how to update the model layer's position to make the change permanent.
Let's formalize the code pattern you just saw. This is the standard, recommended way to perform a basic animation:
// 1. Create the animation object
let positionAnimation = CABasicAnimation(keyPath: "position.x")
// 2. Configure the animation
positionAnimation.fromValue = myView.layer.position.x
positionAnimation.toValue = myView.layer.position.x + 200
positionAnimation.duration = 1.0
positionAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
// 3. **Crucially, update the model layer to the final value.**
// This prevents the "snap-back" effect.
myView.layer.position.x += 200
// 4. Add the animation to the layer.
// The key lets you identify and manage the animation later if needed.
myView.layer.add(positionAnimation, forKey: "moveRight")
There is an alternative approach using animation.fillMode = .forwards and animation.isRemovedOnCompletion = false, but as the objc.io article mentioned, this is generally discouraged. It leaves the animation object attached to the layer indefinitely, which can add overhead and makes the state of your UI harder to reason about because the model layer no longer reflects what's on screen. Always prefer updating the model layer.
Animating Other Layer Properties
The power of this pattern is its versatility. By simply changing the keyPath and the fromValue/toValue types, you can animate a wide range of properties. The video you just watched continues to demonstrate this for scale, rotation, and opacity.
Let's continue with the same video to see how to apply the CABasicAnimation pattern to other common properties.
Watch from 08:16 to 15:21. The video demonstrates how to animate: Scale (08:16 - 10:34) using the "transform.scale" key path and introducing the autoreverses property. Rotation (10:34 - 12:31) using "transform.rotation" and the repeatCount property. Opacity (12:31 - 15:21) using the "opacity" key path, which is analogous to a view's alpha property.
As you saw, the fundamental structure remains the same. This approach gives you access to animate properties that are cumbersome or impossible to animate with UIView blocks, such as:
cornerRadiusborderWidthandborderColorshadowColor,shadowOffset,shadowOpacity, andshadowRadiusstrokeEndandstrokeStarton aCAShapeLayer(which we'll explore in a later module)
UIView.animate vs. CABasicAnimation: Which to Choose?
You now have two powerful animation tools. Here's a quick guide on when to use each:
Use UIView.animate when... |
Use CABasicAnimation when... |
|---|---|
Animating standard UIView properties (frame, alpha, etc.) |
Animating CALayer-specific properties (shadowPath, borderColor). |
| Animating Auto Layout constraints. | You need maximum performance and direct rendering control. |
| You want a simple, convenient block-based syntax. | Creating complex, reusable animation objects or sequences. |
You need interactive, interruptible animations (UIViewPropertyAnimator). |
You need to animate along a CGPath. |
For most day-to-day UI tasks, UIView.animate is sufficient and often simpler. However, for custom controls, visually rich interfaces, or performance-critical drawing, CABasicAnimation is the indispensable tool you'll reach for.
Conclusion
In this lesson, we pulled back the curtain on UIView animations and learned to work directly with the powerful Core Animation framework. You now have the foundational knowledge to create explicit animations with CABasicAnimation.
Key Takeaways:
CABasicAnimationworks directly onCALayerproperties via a stringkeyPath.- Core Animation uses a model layer (the source of truth) and a presentation layer (what's on screen during animation).
- To prevent the "snap-back" effect, you must update the model layer's properties to match the animation's final state when you add the animation.
- The same
CABasicAnimationpattern can be used to animate many properties likeposition,transform,opacity,cornerRadius, andshadowsby simply changing thekeyPathand values.
Preview of the Next Lesson:
We've now animated single properties. But what if you want to animate a view's position, color, and corner radius all at the same time, perfectly synchronized? In our next lesson, we will learn how to group multiple CAAnimation objects to run in parallel using CAAnimationGroup, allowing you to build even more sophisticated and coordinated visual effects.