Animation Completion

The method animate(withDuration:animations:) returns immediately. That is, it starts the animation, but it does not wait for the animation to complete. What if you want to know when an animation completes? For instance, you might want to chain animations together or update another object when the animation completes. To know when the animation finishes, pass a closure for the completion argument. You will use this opportunity to swap the two label references.

In ViewController.swift, update animateLabelTransitions() to use the UIView animation method that has the most parameters, including one that takes in a completion closure.

func animateLabelTransitions() {

    // Animate the alpha
    UIView.animate(withDuration: 0.5, animations: {
        self.currentQuestionLabel.alpha = 0
        self.nextQuestionLabel.alpha = 1
    })
    UIView.animate(withDuration: 0.5,
        delay: 0,
        options: [],
        animations: {
            self.currentQuestionLabel.alpha = 0
            self.nextQuestionLabel.alpha = 1
        },
        completion: { _ in
            swap(&self.currentQuestionLabel,
                 &self.nextQuestionLabel)
    })
}

The delay indicates how long the system should wait before triggering the animation. We will talk about the options later in this chapter. For now, you are passing in an empty array.

In the completion closure, you need to tell the system that what used to be the currentQuestionLabel is now the nextQuestionLabel and that what used to be the nextQuestionLabel is now the currentQuestionLabel. To accomplish this, you use the swap(_:_:) function, which accepts two references and swaps them.

Build and run the application. Now you are able to transition between all of the questions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset