tezvyn:

CAKeyframeAnimation: Animating Through Key States

AI-drafted, machine-checkedSource: developer.apple.comadvanced
CAKeyframeAnimation: Animating Through Key States

CAKeyframeAnimation defines animations with waypoints, not just a start and end. Think of it as a flipbook where you set key frames and the system interpolates. Use it for complex paths, like shaking an icon. Footgun: setting both `path` and `values`.

WHY IT EXISTS Basic animations (CABasicAnimation) are great for moving from state A to state B. But for more complex motion, like an icon shaking or an object tracing a curve, you need to define intermediate points. CAKeyframeAnimation was created to solve this by letting you specify a sequence of states or a path for an animation to follow.

THE MENTAL MODEL Think of CAKeyframeAnimation like a flipbook. Instead of just the first and last page, you draw several key pages in between. Core Animation then smoothly interpolates the frames between your key drawings. You provide these key points either as an array of values (like coordinates or colors) or as a complete CGPath for the object to trace.

HOW IT WORKS You create a CAKeyframeAnimation instance for a specific property, like "position" or "backgroundColor". You then provide the animation's waypoints in one of two main properties. First, you can set the values property to an array of states, like [color1, color2, color3]. Second, for positional animations, you can set the path property to a CGPath object, and the layer's anchor point will follow that path. You can also provide an array of keyTimes (numbers from 0.0 to 1.0) to control the timing and pacing between keyframes.

WHEN TO USE IT Use CAKeyframeAnimation for any animation that is not a simple A-to-B transition. It's perfect for creating a 'shake' effect on a text field by animating its position through a series of small offsets. It's also the tool for moving an object along a complex curve, like a satellite orbiting a planet, or for cycling a property through a specific sequence of colors or opacities.

WHEN NOT TO USE IT For simple animations between two states, such as fading in or moving from left to right, CABasicAnimation is simpler and more efficient. For animations that need to feel physical, with properties like mass, stiffness, and damping, CASpringAnimation is the more appropriate choice.

ONE CANONICAL EXAMPLE A classic use case is making a UI element shake to indicate an error. You create a CAKeyframeAnimation for the "transform.translation.x" key path. You then set its values property to an array of horizontal offsets, like [0, 10, -10, 10, -5, 5, 0]. By setting a short duration, the layer will quickly move back and forth, creating a convincing shake effect without complex position management.

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.