CABasicAnimation: Simple Property Changes Over Time

CABasicAnimation animates a single layer property from a start to an end value. Use it for fading a view (opacity), moving it (position), or scaling it (transform).
WHY IT EXISTS: To provide a simple, declarative way to animate a single property of a CALayer between two states (a "from" value and a "to" value) over a specified duration. It abstracts away the complexity of manually updating property values on each frame for a smooth transition.
THE MENTAL MODEL: Think of CABasicAnimation as setting just two keyframes: a start point and an end point for a single property. Core Animation then handles all the interpolation between them. It's like telling an actor "start at position X, end at position Y, and take 2 seconds to get there." The system figures out all the intermediate steps to make the movement look smooth.
HOW IT WORKS: You create an instance of CABasicAnimation, specifying the keyPath of the property you want to animate, such as "opacity", "position", or "transform.scale". You then set its toValue and, optionally, a fromValue. If fromValue is nil, the animation implicitly starts from the layer's current value. After configuring properties like duration, you add the animation object to a CALayer using its add(_:forKey:) method. The system then takes over rendering the frames.
WHEN TO USE IT: Use CABasicAnimation for any simple, "A-to-B" style animation on a single property. It's perfect for fading elements in or out (opacity), moving them across the screen (position), rotating them (transform.rotation), or resizing them (bounds or transform.scale). It is the simplest tool for the most common animation tasks.
WHEN NOT TO USE IT: Avoid it for complex paths or multi-stage animations. If you need to animate a property through several specific values (A -> B -> C), use CAKeyframeAnimation instead. For animations that need to feel physical, with bounce or springiness, CASpringAnimation is the correct choice. For animating multiple properties together in a synchronized group, use CAAnimationGroup.
ONE CANONICAL EXAMPLE: To fade out a UIView, you animate its backing CALayer's opacity. First, create a CABasicAnimation with the key path "opacity" and set its toValue to 0.0. Set a duration, like 0.5 seconds. Then, add this animation to the layer. The critical footgun to avoid is the "snap back": the animation only affects the temporary presentation state. To make the change permanent, you must also update the model value itself: myView.layer.opacity = 0.0. Without this line, the view would reappear instantly when the animation finishes.
Read the original → developer.apple.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.