动画递增UILabel

时间:2015-10-05 09:59:04

标签: ios swift animation grand-central-dispatch swift2

我想在视图出现时设置UILabel的值的动画。因此我创造了这个功能。

private func animateIncrementUILabel(label: SpringLabel, labelValue: Int, animationPeriod: Float?)
{

    animationPeriod != nil ? animationPeriod! : 40

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {

        for (var i = 0; i < labelValue; i++)
        {
            usleep(UInt32(animationPeriod!)/100 * 1000000)
            dispatch_async(dispatch_get_main_queue(), {
                label.text = String(i)
            })
        }

    })
}

但在我的viewDidAppear方法中调用此方法,如

animateIncrementUILabel(counterLabelOne, labelValue: 20, animationPeriod: 40.0)

它在没有&#34;动画增量&#34;的情况下直接在标签中显示值。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

在这种情况下,请勿使用usleepdispatch_async。我建议您使用dispatch_after

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(i * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    <#code to be executed after a specified delay#>
});

或带有重复选项的NSTimer

NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)

你也可以将一些参数传递给计时器:

func someFunc(){
    var arr = ["one", "two"] 
    var timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("val:"), userInfo: arr, repeats: true)
}

func val(timer: NSTimer){

    //You'll get an array in timer.userInfo
    // arr = timer.userInfo.
    // Now you'll get you data in each index of arr

}