【问题标题】:animate incrementing UILabel动画递增 UILabel
【发布时间】:2015-10-05 09:59:04
【问题描述】:

我试图在视图出现时为 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)

它直接在标签中显示值,没有“动画增量”。

我在这里做错了什么?

【问题讨论】:

  • 删除那些调度块并使用 NSTimer.Schdule 活动而不是睡眠

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


【解决方案1】:

在这种情况下不要使用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

}

【讨论】:

  • 但我想提供几个参数。如何使用 NSTimer 实现这一点?你能举个例子吗?
  • 但是这样我不能强制给出某些参数。都是可选的
猜你喜欢
  • 1970-01-01
  • 2016-07-22
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多