UIView.animateWithDuration不使用信号量执行

时间:2014-12-04 01:11:29

标签: animation swift grand-central-dispatch

我正在尝试编写一个函数,将视图的背景颜色闪烁为白色,然后再恢复为原始颜色。我所拥有的是:

func flashView(view: UIView) {
    var sema = dispatch_semaphore_create(0)
    var color = view.backgroundColor
    println("Animating")
    UIView.animateWithDuration(0.5, animations: { view.backgroundColor = UIColor.whiteColor() }) {
        (success: Bool) in
        println("First block completion")
        UIView.animateWithDuration(0.5, animations: { view.backgroundColor = color }) {
            (success: Bool) in
            println("Nested block completion")
            dispatch_semaphore_signal(sema)
        }
    }
    println("Waiting")
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
    println("Returning")
}

现在,我遇到的是Animating消息将显示后跟Waiting。第一个animateWithDuration块永远不会被执行(不用说嵌套的块也不会执行。但是,根据Apple自己的documentationUIView.animateWithDuration发生在一个单独的线程上。所以,我的理解,是信号量应该等待,animateWithDuration应该在一个单独的线程上完成,并且该函数应该返回(等待在嵌套闭包中发出信号的信号量之后)。我有什么误解?

谢谢!

1 个答案:

答案 0 :(得分:2)

动画块在主线程中执行,而dispatch_semaphore_wait则阻塞主线程。 所以动画块永远不会执行。

这是一个解决方案。

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
        println("Returning")
    })

其他解决方案如下:
How do I wait for an asynchronously dispatched block to finish?

相关问题