Timing Functions

The acceleration of the animation is controlled by its timing function. By default, animations use an ease-in/ease-out timing function. To use a driving analogy, this would mean the driver accelerates smoothly from rest to a constant speed and then gradually slows down at the end, coming to rest.

Other timing functions include linear (a constant speed from beginning to end), ease-in (accelerating to a constant speed and then ending abruptly), and ease-out (beginning at full speed and then slowing down at the end).

In ViewController.swift, update the animation in animateLabelTransitions() to use a linear timing function.

UIView.animate(withDuration: 0.5,
    delay: 0,
    options: [.curveLinear],
    animations: {
        self.currentQuestionLabel.alpha = 0
        self.nextQuestionLabel.alpha = 1

        self.view.layoutIfNeeded()
    },
    completion: { _ in
        swap(&self.currentQuestionLabel,
             &self.nextQuestionLabel)
        swap(&self.currentQuestionLabelCenterXConstraint,
             &self.nextQuestionLabelCenterXConstraint)

        self.updateOffScreenLabel()
})

Now, as opposed to using the default ease-in/ease-out animation curve, the animation will have a linear animation curve. Build and run the application. The difference is subtle, but it is noticeable if you watch for it.

The options parameter takes in a UIViewAnimationOptions argument. Why is this argument in square brackets? There are many options for an animation in addition to the timing function. Because of this, you need a way of specifying more than one option – an array. UIViewAnimationOptions conforms to the OptionSet protocol, which allows you to group multiple values using an array.

Here are some of the possible animation options that you can pass into the options parameter.

Animation curve options

Control the acceleration of the animation. Possible values are:

  • UIViewAnimationOptions.curveEaseInOut

  • UIViewAnimationOptions.curveEaseIn

  • UIViewAnimationOptions.curveEaseOut

  • UIViewAnimationOptions.curveLinear

UIViewAnimationOptions.allowUserInteraction

By default, views cannot be interacted with when animating. Specifying this option overrides the default. This can be useful for repeating animations, such as a pulsing view.

UIViewAnimationOptions.repeat

Repeats the animation indefinitely; often paired with the UIViewAnimationOptions.autoreverse option.

UIViewAnimationOptions.autoreverse

Runs the animation forward and then backward, returning the view to its initial state.

Be sure to check out the Constants section of the UIView Class Reference to see all of the possible options.

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

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