带有持续时间的循环动画,Swift 4

时间:2019-04-09 21:10:16

标签: swift loops animation race-condition

我有一张图像,想要连续移动10次。每次我希望它执行检查时,如checkForStuff的打印语句所示。我注意到循环开始并且在10个动作中的第一个动作发生时超时。关于如何链接动画的任何想法,还是我需要在顺序闭包中手动编写每个链?

@objc func moveBox(sender: UIButton!) {
    print("Started")
    let imageToMove = UIImageView()
    imageToMove.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
    imageToMove.backgroundColor = .red
    self.view.addSubview(imageToMove)

    var counter = 0
    var altitude = 100


    while counter <= 10 {
        print("looping")
        UIView.animate(withDuration: 0.5, animations: {
            imageToMove.frame = CGRect(x: 50, y: altitude, width: 50, height: 50)
        }, completion: { finished in
            counter += 1
            altitude += 50
            print("Check For Stuff")
        })
    }

}

简而言之,应将像素向下移动50个像素,执行关闭操作,然后再次向下移动50个像素。一遍又一遍。

1 个答案:

答案 0 :(得分:1)

尝试@matt建议的递归

 func animate(view: UIView, altitude: Int, numberOfTime: Int ) {

        if numberOfTime == 0 { return }

        UIView.animate(withDuration: 0.5, animations: {

            view.frame = CGRect(x: 50, y: altitude, width: 50, height: 50)
        }, completion: { finished in
            self.animate(view: view, altitude: altitude + 50, numberOfTime: numberOfTime - 1)
        })
    }

将此用作

@objc func moveBox(sender: UIButton!) {
    print("Started")
    let imageToMove = UIImageView()
    imageToMove.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
    imageToMove.backgroundColor = .red
    self.view.addSubview(imageToMove)

    animate(view: imageToMove, altitude: 100, numberOfTime: 10)
}