RubberDucky4444 RubberDucky4444 - 6 months ago 44
Swift Question

Swift combine animations into one with completion

I have 5 animations that are just objects on the page that fall down after the user taps the login button. I put an 0.3 incremental delay on each following one. I was wondering if there was a cleaner and more efficient way of writing this code.

func loggedInAnimate1(){

UIView.animateWithDuration(2,
delay: 0.0,
options: .CurveEaseIn,
animations: {
self.newUser.center.y += self.view.bounds.width

}, completion: nil)

}

func loggedInAnimate2(){

UIView.animateWithDuration(2,
delay: 0.3,
options: .CurveEaseIn,
animations: {
self.loginButton.center.y += self.view.bounds.width

}, completion: nil)

}

func loggedInAnimate3(){

UIView.animateWithDuration(2,
delay: 0.6,
options: .CurveEaseIn,
animations: {
self.loginPasswordTextField.center.y += self.view.bounds.width

}, completion: nil)

}

func loggedInAnimate4(){

UIView.animateWithDuration(2,
delay: 0.9,
options: .CurveEaseIn,
animations: {
self.loginEmailTextField.center.y += self.view.bounds.width

}, completion: nil)

}

func loggedInAnimate5(){

UIView.animateWithDuration(3,
delay: 1.2,
options: .CurveEaseIn,
animations: {
self.logo.center.y += self.view.bounds.height

}, completion: nil)

}


and on the last one i want to call another function...is this all possible? Thanks

Answer

You could use the completion closure to fire the next animation. That way you don't need to use a delay, and you can nest the animations.

UIView.animateWithDuration(2, delay: 0, options: .CurveEaseIn, animations: {
    self.newUser.center.y += self.view.bounds.width
}, completion: { _ in
    UIView.animateWithDuration(2, delay: 0, options: .CurveEaseIn, animations: {
        self.loginButton.center.y += self.view.bounds.width
    }, completion: { _ in
        // And so on...
    })
})
Comments