Bailey Miller Bailey Miller - 6 months ago 76
Swift Question

Performing a segue after animation is finished

I'm trying to perform a segue after an animation is finished. Here is the code I have in viewDidAppear:

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)

imageViewAnimated.startAnimating()


if label.center != CGPoint(x:50, y:10) {

UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.0, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in
self.label.center = self.view.center

}, completion: nil)

UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.0, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in
// self.label.center = CGPoint(x: 50,y:300)
self.label.alpha = 0.0

}, completion: nil)
}

if label.alpha == 0.0 {
UIView.animateWithDuration(0.5, delay: 10.0, usingSpringWithDamping: 0.0, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in

self.performSegueWithIdentifier("backSegue", sender: self)

}, completion: nil)
}
}


So basically I have a label that's moving down and fading out(the first and second animateWithDuration), and then I want the Segue to occur after the label is faded out and the other animation is done. Right now the segue is happening, but it does it right away and doesn't wait no matter how much I increase the delay.

Answer

You are calling the segue in the wrong place. You want something like this:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    imageViewAnimated.startAnimating()

    if label.center != CGPoint(x:50, y:10) {
        UIView.animateWithDuration(2.0, delay: 0.0, usingSpringWithDamping: 0.0, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in
            self.label.center = self.view.center
        }, completion: nil)

        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.0, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: { () -> Void in
            //                self.label.center = CGPoint(x: 50,y:300)
            self.label.alpha = 0.0
        }, completion: { finished in
            self.performSegueWithIdentifier("backSegue", sender: self)
        })
    }
}