Posted on March 10th 2020 by Chris Eidhof
In the fifth of our Thinking in SwiftUI challenges, we asked you to animate a path.
SwiftUI Challenge #5: Path Animations ⌚️
Animate a path between two starting points, in a motion that doesn’t jump between them.
Reply with your solution, and we’ll post ours next Tuesday. 👍
Starter code: https://t.co/aSLm1bS49G pic.twitter.com/E8v0onpbdD
— objc.io (@objcio) March 4, 2020
SwiftUI Challenge #5: Path Animations ⌚️
Animate a path between two starting points, in a motion that doesn’t jump between them.
Reply with your solution, and we’ll post ours next Tuesday. 👍
Starter code: https://t.co/aSLm1bS49G pic.twitter.com/E8v0onpbdD
We started the challenge with code that draws a line. The starting point changes based on a boolean property, but despite the withAnimation
, the path itself doesn’t animate:
To animate a path, we need to tell SwiftUI which properties are animatable. One way to do this is by wrapping the path in a custom Shape
. We create a Line
shape with properties for both the line’s start and end points:
To animate the start
and end
properties, we need to expose them via animatableData
, and the type of animatableData
needs to conform to the VectorArithmetic
protocol. Unfortunately, CGPoint
does not conform to VectorArithmetic
, and it’s bad practice to add this conformance ourselves: you’re not supposed to conform types you don’t own to protocols you don’t own, even though in this case, there wouldn’t be much harm in it.
Luckily, CGPoint
does conform to Animatable
, so we can use its animatableData
. We can now make both points of the Line
animatable by creating an animatable pair out of the two CGPoint.Animatable
values:
Our new book, Thinking in SwiftUI, discusses the animation system in more detail in chapter six. You can join the early access here.
Learn
Follow
More