快速循环延迟无法正常工作

时间:2017-03-21 22:33:33

标签: swift loops delayed-execution

我正在尝试动画UIImageView在屏幕上移动。为了使运动平稳,我需要使用大约60个增量。该代码适用于增量0-10,每次新的增量在一秒钟暂停后发生。但是,对于增量10-20,它会暂停2秒,然后执行两次循环。对于21-30,它暂停3秒并执行循环三次,依此类推。以下是我的循环:

    for i in 0...30 {
        let when = DispatchTime.now() + .seconds(i)
        DispatchQueue.main.asyncAfter(deadline: when) {
            let date = Date()
            let calendar = Calendar.current
            let second = calendar.component(.second, from: date)
            print("delay count = \(i), time = \(second))")
            self.ballView.frame = CGRect(x: ballPositionX, y: self.view.frame.size.height * 0.45, width: self.view.frame.size.width * 0.2, height: self.view.frame.size.height * 0.2)
            ballPositionX = ballPositionX + ballMoveX
        }
    }

通过比较索引(延迟计数)和循环发生时的秒(时间),您可以在控制台日志中看到循环执行中的附加延迟。

   delay count = 0, time = 10)
   delay count = 1, time = 11)
   delay count = 2, time = 12)
   delay count = 3, time = 13)
   delay count = 4, time = 14)
   delay count = 5, time = 16)
   delay count = 6, time = 17)
   delay count = 7, time = 18)
   delay count = 8, time = 19)
   delay count = 9, time = 19)
   delay count = 10, time = 21)
   delay count = 11, time = 22)
   delay count = 12, time = 22)
   delay count = 13, time = 25)
   delay count = 14, time = 25)
   delay count = 15, time = 27)
   delay count = 16, time = 27)
   delay count = 17, time = 29)
   delay count = 18, time = 29)
   delay count = 19, time = 31)
   delay count = 20, time = 31)
   delay count = 21, time = 33)
   delay count = 22, time = 33)
   delay count = 23, time = 33)
   delay count = 24, time = 37)
   delay count = 25, time = 37)
   delay count = 26, time = 37)
   delay count = 27, time = 40)
   delay count = 28, time = 40)
   delay count = 29, time = 40)
   delay count = 30, time = 43)

我已经查看了循环中延迟的其他实现,但通常它们的循环永远不会超过10个循环。

1 个答案:

答案 0 :(得分:0)

实现动画的最佳方法是通过设置参数来查看您想要设置动画,然后使用其中一个重载调用UIView.animate并调用更新特定部分

如果您要更新布局,请拨打layoutIfNeeded

这是一个例子:

//calculating final frame (origin and size)
let x = ballPossitionX * 30
let y = self.view.frame.size.height * 0.45
let width = self.view.frame.size.width * 0.2
let height = self.view.frame.size.height * 0.2

ballView.frame = CGRect(x: x, y: y, width: width, height: height

let animationTime = 2.0

UIView.animate(withDuration: animationTime) {
   self.view.layoutIfNeeded()
}

还有一些动画属性,如alpha,可以直接添加到动画块中