How to animate incrementing number in UILabel in swift
Asked Answered
N

2

7

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)
    }
}
Nonnah answered 2/4, 2016 at 6:56 Comment(2)
Can you describe a little more precisely how it should look? Should e.g. the old value fade out while the new one fades in at the same place? Or should the old one turn aside while the new one turns in, like with a picker? Or what is your goal?Aquatic
Possible duplicate of: #33632766Skin
F
2

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

Fanniefannin answered 21/11, 2016 at 1:1 Comment(0)
C
1

Please check this:

func countAnimation(timer: NSTimer)
{
    UIView.transitionWithView(label,
                          duration: 1.0,
                          options: [.CurveEaseInOut],
                          animations: { () -> Void in
                          // Write your code here
    }, completion: nil)

}
Constable answered 21/11, 2016 at 5:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.