I wrote an article the other day in which I talked about building basic bar charts: “Linking Animations together to Build Bar Charts in SwiftUI.” I am not going to post the final code again, but I will show what we managed to build.
In short, it’s an animated, auto-coloured, data-refreshing bar chart. I kept it sweet and short, but couldn’t help but feel I wanted to do more.
Let’s do a new brief based on the bar chart theme. Here is a wish list:
Some of these things are easy, some less so — and at least one is going to be almost impossible — so let’s get stuck in.
I going to start with text labels since bar charts showing just values aren’t that useful. I want to add an axis label while I’m about it, too. We’re after this.
Animated bar chart with axis and labels
OK, it’s not perfect… the axis shouldn’t really be animated like that, but it’s a move forward. How did I do it? Obviously, it’s based on the code presented in the previous article, only I swapped the axis, added a text field as a second published object, and made a few minor changes to the layout code.
Bon, that’s half the wish list already — told you some of the wishes are not so difficult. What about the second half? To do that, I am going to use the Combine framework available in SwiftUI 1.0 and create a collection of actions with it.
var hideColumn = PassthroughSubject<String,Never>()
var showColumn = PassthroughSubject<String,Never>()
var changeColumn = PassthroughSubject<(String,String),Never>()
var changeFigure = PassthroughSubject<(String,Int),Never>()
And indeed, add code to match those actions and change our bar chart. Now I use a switch statement to test everything (SwiftUI 2.0 only).
The code will tell the bar chart to hide two columns, bring one back, change a couple of column names, and then change some of the values held against the grapes, pineapples, and peaches categories. Let’s watch it in action.
Animated bar chart with name changes, value changes, column changes
There is still work to do, but we’re making progress. A couple of outstanding issues:
Let’s keep going. Continuing on the same path, I can use the Combine framework to add three more actions to our code.
#animation #mobile #programming #ios #swift