Posted on March 16th 2020 by Chris Eidhof
In the sixth of our Thinking in SwiftUI challenges, we asked you to animate a line graph.
SwiftUI Challenge #6: Line Graph Animations 📈
Implement and animate a line graph. For a bonus challenge: add a small dot that follows the tip of the graph.
Reply with your solution, and we’ll post ours next Tuesday. 👍 pic.twitter.com/M6HJVN3lE9
— objc.io (@objcio) March 11, 2020
SwiftUI Challenge #6: Line Graph Animations 📈
Implement and animate a line graph. For a bonus challenge: add a small dot that follows the tip of the graph.
Reply with your solution, and we’ll post ours next Tuesday. 👍 pic.twitter.com/M6HJVN3lE9
As a first step, we’ll create a shape for the line graph. This shape takes an array of data points (normalized to 0...1
). Any points that are outside this range are drawn outside of the proposed rectangle rect
. For clarity, we pulled out the function that computes a CGPoint
for a given data point.
SwiftUI has built-in support for trimming shapes using the .trim
modifier: this trims the path of the shape to the specified start and end points. We keep a constant starting point, 0
, but vary the end point during the animation (from 0
to 1
). Since the trim
modifier has built-in support for animating the start and end points, we can animate the graph simply by animating between a to
value of 0
and 1
. Because the graph is defined as a Shape
, we can use the built in modifiers to style it: stroke it with a red color, fix it to an aspect ratio, add a border, and apply some padding:
That’s all we need for our line graph — or any shape, really — to animate:
Our new book, Thinking in SwiftUI, discusses the animation system in more detail in chapter six. You can buy it here.
by Chris Eidhof and Florian Kugler
New
$39
Stay up-to-date with our newsletter or follow us on Twitter.
Nov 27th, 2020
30% on everything until Monday
Nov 23rd, 2020
How grids lay out their content.
Nov 9th, 2020
Flexibility Defined
Browse the Archive
objc.io publishes books, videos, and articles on advanced techniques for iOS and macOS development.
Learn
Follow
More