ios - 动画递增 UILabel

标签 ios swift animation grand-central-dispatch swift2

我正在尝试在 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)

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

我在这里做错了什么?

最佳答案

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

}

关于ios - 动画递增 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945792/

相关文章:

ios - 新 iOS 项目模板中的 Xcode Storyboard

iOS 编程中心 UIView 组

ios - strip 创建用户 firebase 云函数

ios - Swift 错误中的 Objective-C 完成 block

iOS 重复调用 CGContext.save/restoreGState(又名 CGContextSave/RestoreGState)导致锯齿

swift - queryOrdered 并不总是以正确的顺序返回 tableViewCell 上的数据

animation - 我如何在 Angular 2 中为路由器组件使用动画

ios - 核心数据重复实体

ios - 隐藏堆栈 View 时,并非所有内容都会在堆栈 View 中进行动画处理

animation - 了解用于排序/过滤元素组的 CSS3 转换/动画的任何优秀示例