21 October

UIViewPropertyAnimator in iOS 10

Introducing 10th version of iOS, Apple gave developers a new tool – UIViewPropertyAnimator. It enhances options of creating animation in our application. New options include stopping animation and resuming it (also with other time parameters), finishing animation at any time, reversing animation or moving it to any chosen moment, and many more. Another novelty is the fact that apart from previously used timing options of animation, such as EaseInEaseOut we now also have the ability to define our own time function based on checkpoints of cubic function.

To create an animation using animator we create its instance:

let animator = UIViewPropertyAnimator(duration: 1, curve: .linear) {
	//Animations
}

We can also use a constructor, which allows us to define control points for a custom time function:

let animator = UIViewPropertyAnimator(duration: 5,
                                       controlPoint1: CGPoint(x: 0.3, y: 1),
                                       controlPoint2: CGPoint(x: 0.7, y: 0.2)) {
        //Animations
 }

o add a block executed after finishing animation we call addCompletion:

animator.addCompletion { (UIViewAnimatingPosition) in
         //some code
}

What is new here is the fact that our block gets a parameter with position of animation. Available positions are start, end and current position.

After configuring our animator we should start the animation. To do this, we call function startAnimation on our animator:

animator.startAnimation()

After starting our animation, we can pause it – we do it using pauseAnimation function:

animator.pauseAnimation()

We can also stop it using stopAnimation function:

 animator.stopAnimation(true)

The function takes a parameter withoutFinishing which allows us to decide whether we want the animation to be finished when stopped. If it is stopped, the animated objects will remain in their current position. Otherwise, we finish the animation on our own, using finishAnimation function:

animator.finishAnimation(at: .end)

Taken parameter determines the position of the end – available positions are start, end, and current, just like with finishing a block.

After pausing the animation we can resume it with function startAnimation, but there is also a more advanced option, that is using a function continueAnimation, which also offers a change of time parameters and length of the remaining part of the animation:

let timing = UICubicTimingParameters(animationCurve: .linear)
animator.continueAnimation(withTimingParameters: timing, durationFactor: 1)

Another way is to reverse the animation in the opposite direction. To accomplish this we change the property isReversed of our animator:

animator.isReversed = true

To sum up – the introduction of the new class of UIViewProperty animator offers some really cool features that undoubtedly can make creating animations much easier for developers.