我正在尝试在 View 出现时为 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)
它直接在标签中显示值,没有“动画增量”。
我在这里做错了什么?
最佳答案
在这种情况下不要使用usleep
和dispatch_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
}
关于ios - 动画递增 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945792/