Swift:动画延迟for循环不起作用?

时间:2017-02-20 18:44:21

标签: swift for-loop delay

好的,我看了很多其他帖子但是我的方法不起作用。我有一系列图像(2-7.png),我试图连续动画,每个图像之间有延迟。要做到这一点,我有:

 for i in 2...7
            {
                        //code that runs after the transition is complete here
                        var bubView = UIImageView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
                        bubView.image = UIImage(named: "\(i).png")
                        //bubView.backgroundColor = UIColor.black
                        bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)
                        self.addSubview(bubView)

                        UIView.animate(withDuration: 0.4, delay: 2.0, usingSpringWithDamping:
                            0.6, initialSpringVelocity: 1.25, options: [], animations: {
                                //thing being animated
                                bubView.frame = CGRect(x: 0, y: 0, width: self.screenSize.width, height: self.screenSize.width)
                               bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)


                        }, completion: { finished in

                            })


        }

我也试过在动画中没有延迟,只是在for循环的开始处延迟了一段时间,但是这一切都让所有的图像立刻生成动画。他们都被推迟了2s,然后他们都进来了。

如何逐个延迟每一个?

2 个答案:

答案 0 :(得分:1)

你给他们所有人制作了相同的动画,所以他们同时发生了所有动画。如果您希望它们单独制作动画,请尝试以下操作:

设置延迟:到2.0 * Double(i)

答案 1 :(得分:0)

您可以同时设置所有动画。要实现您想要的效果,您可以根据Gaston提到的i设置延迟或创建递归函数

func animateView(startWithView : Int = 2) {
  //code that runs after the transition is complete here
  var bubView = UIImageView(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
  bubView.image = UIImage(named: "\(startWithView).png")
  //bubView.backgroundColor = UIColor.black
  bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)
  self.addSubview(bubView)

UIView.animate(withDuration: 0.4, delay: 2.0, usingSpringWithDamping:
    0.6, initialSpringVelocity: 1.25, options: [], animations: {
        //thing being animated
        bubView.frame = CGRect(x: 0, y: 0, width: self.screenSize.width, height: self.screenSize.width)
        bubView.center = CGPoint(x: bubView.center.x, y: self.bounds.height * 0.69)


}, completion: { finished in
    if startWithView < 7 {
        animateView(startWithView: startWithView + 1)
    }
})
}

然后致电

animateView()

考虑更改输入,使其更具可重用性。 我采用这种解决方案,但加斯顿的解决方案更容易实施。