Swift 3: So I Wanted To Animate A Label…
AKA: Why I Love CADisplayLink, And You Should Too!
Have you ever needed a
UILabel to keep track of an arbitrary numerical value? If you’ve ever built an iOS app, my guess is that you have. But if you’ve ever wanted to animate between values, you probably tapped into
CATransition, fading or flipping the label during updates.
I’ve wanted to animate a
UILabel's contents many times. Whenever I’m writing an app I always pay too much attention to detail. I get hung up on the little things, and this time is no different to any other.
Years ago now, I found a pod that did exactly what I wanted. At the time, it was perfect. I just dropped it in and off I went. My score label started at X and ticked up or down, until it reached the destination value.
On Saturday at NSCamp, I needed this behaviour once more. While there were a couple of Swift versions now available, none had been properly updated for Swift 3. So I took it upon myself to port it over from the Objective-C original, with some Swift-y improvements.
I detest porting things from Objective-C to Swift, without harnessing any of Swift’s benefits. In my rewrite, I utilised
file private, so as to better illustrate what different variables are for, and just so I had an excuse to
try! some of the new goodies available. It was also an interesting exercise in remembering that as of late, the
enum style-guide changed from
namingEveryCaseLikeThis. I kept catching myself not remembering it, and it irritated me to no end.
I’m also a bit of a purist. I love trying, however futilely, to keep my project using the one language. Meaning, a Swift project should be written in Swift and nothing else. The same goes in reverse for my Objective-C projects. I find that mixing the two languages creates mess and is the cause of unnecessary context switching. But that’s just my opinion. 👌
How It Works
How this object works is quite simple. It utilises a
CADisplayLink, which will refresh the label at the native cadence of the display, each time the value of the label is to be modified. This, in combination with some fancy math, gives us a nice animation curve during the count. The default option here is
.easeInOut which starts off slow, speeds up, then slows down before the end. The result being, that you can animate a
UILabel's contents from one number to another very easily. It’s so pretty!
Bonus: You can supply a
customFormatBlock which allows you to edit the default formatting of the
String. Keep in mind that this will override the
decimalPoints value you may have set.
Here’s The Code
How To Use
label.countFromZero(to: 200, duration: 10)
label.count(from: 400, to: 500, duration: 900)
Note that the
duration parameter is optional. If you don’t supply one, the object property will be used instead.
If you liked this post, please consider recommending it. I notice each one and appreciate them quite a lot. Thank-you!