animateWithDuration完成块一次又一次地触发

时间:2016-03-23 00:39:07

标签: ios animation completionhandler animatewithduration

我有一点动画,当动画结束时,我希望应用程序自动推送下一个ViewController。那么ViewController连续8次被推上了!它非常疯狂。

这里是代码:

     if CGRectIntersectsRect(whichButton.frame, targetZoneImgView.frame) {
        panGesture.cancelsTouchesInView = true
        let buttonSnapX = UIScreen.mainScreen().bounds.width / 2.0 - 35.0
        let buttonSnapY = UIScreen.mainScreen().bounds.height - 122.0

        UIView.animateWithDuration(0.75, delay: 0.0, 
                usingSpringWithDamping: 0.1, 
                 initialSpringVelocity: 0.0, 
                               options: UIViewAnimationOptions.CurveEaseOut, 
                            animations: {
                                 myButton.frame.origin.x = buttonSnapX
                                 myButton.frame.origin.y = buttonSnapY
                            }, completion: { (finished: Bool) -> Void in
                                  print("Animation done!")
                                  let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                                  let coursesScreen = storyBoard.instantiateViewControllerWithIdentifier("coursesScreen") as! CoursesVC                  
                                  self.navigationController!.pushViewController(coursesScreen, animated: true)
                               }
                           )

print("Animation done!")语句也连续8-9次触发,所以它与我推动ViewController的事实无关。我拿出了ViewController代码 - 它仍在发生。

基本上,我放入completion任何连续发射了很多次。

世界上到底发生了什么?

1 个答案:

答案 0 :(得分:0)

您可以输入falsefinished变量的完成块。只需添加一个基本检查:

UIView.animateWithDuration(0.75, delay: 0.0, 
                usingSpringWithDamping: 0.1, 
                 initialSpringVelocity: 0.0, 
                               options: UIViewAnimationOptions.CurveEaseOut, 
                            animations: {
                                 myButton.frame.origin.x = buttonSnapX
                                 myButton.frame.origin.y = buttonSnapY
                            }, completion: { (finished: Bool) -> Void in
                                 if finished {
                                    print("Animation done!")
                                    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                                    let coursesScreen = storyBoard.instantiateViewControllerWithIdentifier("coursesScreen") as! CoursesVC                  
                                    self.navigationController!.pushViewController(coursesScreen, animated: true)
                                 } else {
                                    print("Animating...")
                                 }
                            }
                          )