Advanced Keyframe Animations in SwiftUI
iOS 17 was easily the best year SwiftUI ever had. It’s the gift that keeps on giving. We got Observation, advanced Mapping, and, best of all, Metal Shaders! One neglected, but incredibly powerful part of this release was something I’ve been wanting to write about for ages: Keyframe Animations! These are an advanced kind of animation that gives you total control. Vanilla SwiftUI animation interpolates between from and to values when some state changes, defined by a simple timing curve. With keyframes, you can fully define the path taken by a movement, a transformation, or a value over time, with different timing curves for every part of a movement. This brings a whole ‘nother level of customisation and composability! Keyframe animations contain a series of tracks. These define a timeline of points, which define exactly how a property will vary between each segment. Moving an object from point A to point B, you can, for example:
You can orchestrate the same animations for virtually any property such as size, opacity, scale, 3D rotation, and even hue. This is great if your properties conform to Animatable. But there are instances where you might be asked to animate something arbitrary, like a flip-book animation switching between many images at once. Perhaps your designer sadistically demanded an accelerating flipping speed for this animation. SwiftUI provides a lesser-known API that makes this an absolute cakewalk. You can read out values from keyframe animation tracks and apply them to anything, anywhere. After today, there will be nothing you can’t animate. In a minute, I’m going to bang on about: To demonstrate everything, I created a sample project that demonstrates the various ways you can apply the keyframe APIs in your code:
Continue reading this post for free in the Substack app |