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)
    }
}

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

在这里输入图像描述

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


请检查这一点:

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

}
链接地址: http://www.djcxy.com/p/91150.html

上一篇: Elastic Beanstalk默认设置上的SSL证书

下一篇: 如何在swift中动画UILabel中的递增数字