Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate incrementing number in UILabel in swift

I have a label showing a number and I want to change it to a higher number, however, I'd like to add a bit of flare to it. I'd like to have the number increment up to the higher number with an ease-in-out curve so it speeds up then slows down. Please, how to implement this in swift, Here is my code. Thanks.

 let newValue : Double = 1000 
 let oldValue : Double = 500 

 timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("countAnimation:"), userInfo: ["oldValue":oldValue, "newValue": newValue],  repeats: true)

func countAnimation(timer: NSTimer)
{
    let dict = timer.userInfo as? [String:AnyObject]
    var OldTotalValue : Double = (dict!["oldValue"] as? Double)!
    let newTotalValue : Double = (dict!["newValue"] as? Double)!

    OldTotalValue = OldTotalValue + 10


    if newTotalValue < OldTotalValue
    {
        timer.invalidate()
    }
  else

    {
         mylabel.text =  String(OldTotalValue)
    }
}
like image 916
Ravi Kanth Manne Avatar asked Apr 02 '16 06:04

Ravi Kanth Manne


1 Answers

I am not entirely familiar with swift. But I have implemented this previously using a parabolic curve.

In detail more or less what is happening is basic algebra. You have a graph with a value x on one axis and then y in the time axis. You want the time delay between each animation to increase until it reaches a plateau.

For example:

x=1 delay= 100ms, x=2 delay =200ms, x=3 delay=310ms, x=4 delay=430ms

notice that every increase is more than the previous.

Mathematically to get such a slope, you could sit in front of a formula such as:

y = -x + x^2

enter image description here

and play around with it until you get an output such that for every increment of x your delay corresponds to a nice slow down that will look clean on an animation.

Thankfully Apple as included libraries that will do this, I found it with a quick search:

 UIViewAnimationOptions.CurveEaseOut

This library will give you a curve that starts quickly then slows down, here is the rest of the Apple Documentation

like image 78
Konstantino Sparakis Avatar answered Oct 02 '22 07:10

Konstantino Sparakis