-1

我的代码有一个问题,下面是一个简化版本。我希望在“1”之前打印“2”。然而,事实并非如此。

这是否与代码实际上不是从上到下运行的事实有关?

if moveConclusion.patternDetected == true {
    for i in 0...8 {
        if pressedArray[i] {
            self.panlButtons[i].backgroundColor = UIColor.clear

            UIView.animate(withDuration: 0.1, animations:{
                self.panlButtons[i].backgroundColor = self.correctColour
                //self.panlButtons[i].transform = CGAffineTransform(rotationAngle: CGFloat.pi / -12)
            }, completion: { finished in
                UIView.animate(withDuration: 0.1, animations:{
                    self.panlButtons[i].backgroundColor = UIColor.clear
                    // self.panlButtons[i].transform = CGAffineTransform(rotationAngle: CGFloat.pi / 12)
                    print("2")
                })
            })
        }
    }
    print("1")
}

输出:

1
2
2
2
...

4

3 回答 3

3

调用UIView.animate 命令动画;它不执行它。动画引擎将执行它 - 稍后。您将两个块交给动画引擎稍后执行,这意味着您所有代码都结束了(从技术上讲,这是下一个屏幕刷新帧出现并且当前 CATransaction 提交时):

  • animations块将在您的所有代码完成后运行,并且该动画开始了。

  • completion块将在动画结束后运行(这就是“完成”的意思)。

于 2018-06-20T18:06:33.717 回答
0

这是因为print("2")在此代码开始后大约 0.1-0.2 秒执行,但print("1")发生在 for 循环执行之后。

动画不与 for 循环同步执行。这print("2")将在第二个动画期间发生,但到那时,for 循环已完成并print("1")已执行。

于 2018-06-20T17:58:48.690 回答
0

UIView.animate在主线程上运行并且是异步的。因此,一旦调用该代码,它就会将其分派到 NEXT 运行循环(在 this 函数终止之后,这意味着在整个 for 循环之后)。

换句话说,UIView.animate调用本质上只是将它排队等待下一个运行循环。并且该print("1")语句仍然出现在当前的运行循环中。

然后运行动画块,一旦动画块完成,完成块运行。因此,就 CPU 处理而言,2 的打印结果是 WAAAAAY,这绝对是预期的行为。

于 2018-06-20T18:03:28.527 回答