Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 52

Interactive Animations with `UIViewPropertyAnimator`

Recommended resources

Hello! Welcome to the first lesson in our new module, "Interactive Animations and Transitions."

In the previous module, we explored the powerful world of Core Animation. We learned to create animations with CABasicAnimation and orchestrate them with CAAnimationGroup. While excellent for complex, pre-defined visual effects, these tools are fundamentally "fire-and-forget." Once you start a CAAnimation, it's difficult to pause, reverse, or let a user control its progress with a gesture.

Today, we shift our focus to a modern UIKit API designed to solve exactly that problem. Our goal is to explain the benefits of UIViewPropertyAnimator for creating interactive and interruptible animations. This class provides an object-oriented approach that gives you fine-grained control over the entire animation lifecycle, bridging the gap between simple UIView animations and the low-level power of Core Animation.

Why Do We Need a New Animation API?

Before diving into the code, let's establish why interactive animations are so valuable and what makes UIViewPropertyAnimator the right tool for the job.

Building Better iOS App Animations

The article "Building Better iOS App Animations" on Medium offers a great perspective on why interactivity matters in animations.

Please read the introduction and the section titled "Why Create Interactive Animations?". This will set the stage for why direct manipulation feels so natural and powerful in a user interface.

As the article points out, direct manipulation makes an app feel more responsive and intuitive. UIViewPropertyAnimator, introduced in iOS 10, was created specifically to facilitate these kinds of animations. It addresses the shortcomings of older APIs:

  • UIView.animate: Simple and easy to use, but you have no control once the animation starts.
  • CAAnimation: Powerful and performant, but not designed for interactivity. Pausing, scrubbing, or reversing is complex to implement correctly.

UIViewPropertyAnimator combines the best of both worlds. It gives you an animator object that represents the animation. You can hold onto this object, inspect its state, and manipulate it long after it has started.


The Core Benefits: Interactivity, Interruptibility, and More

UIViewPropertyAnimator is built on a state machine, which allows it to be paused, resumed, and stopped in a predictable way.

UIViewPropertyAnimator State Diagram
This diagram shows the three states of a `UIViewPropertyAnimator`: `inactive`, `active`, and `stopped`. Methods like `startAnimation()` and `pauseAnimation()` transition the animator between these states, giving you explicit control over its lifecycle.

This stateful nature provides several key benefits that directly enable advanced interactive animations:

  • Interactive: You can "scrub" through an animation by setting its fractionComplete property, which is perfect for linking an animation's progress to a user gesture.
  • Interruptible: An animation can be paused at any time. You can then change its parameters or even add new animations before resuming.
  • Reversible: You can change the direction of an animation mid-flight by setting its isReversed property.
  • Timing Control: You can modify the animation's timing curves and duration dynamically.

Let's explore the technical underpinnings that make this possible.

Popping into UIViewPropertyAnimator

Arkadiusz Holko's article, "Popping into UIViewPropertyAnimator", provides an excellent technical explanation of how the animator works under the hood.

Read the sections titled "What Makes UIViewPropertyAnimator Better" and "It's the Way Forward". The key insight here is that the animator creates a standard CAAnimation but gives us a powerful API to control its progress, rather than letting Core Animation run it to completion on its own.

The crucial takeaway is that UIViewPropertyAnimator doesn't reinvent the wheel; it puts a powerful new steering wheel on the high-performance engine of Core Animation that you're already familiar with.


The Key to Interactivity: fractionComplete

The single most important property for creating interactive animations is fractionComplete. It's a CGFloat value between 0.0 and 1.0 that represents the current progress of the animation. By manually setting this property, you can drive the animation from an external source, like a slider or a pan gesture.

Let's see this in action. The following video demonstrates how to control an animation's progress using a simple UISlider.

Swift Tutorial - UIViewPropertyAnimator - Control Your Animations

In this video, "Swift Tutorial - UIViewPropertyAnimator - Control Your Animations" from Sean Allen, you'll see a clear, practical demonstration of the fractionComplete property.

Watch the first minute (0:00-1:12) to see the final interactive effect. Then, watch from 2:08 to 6:10, where the animator is created and its fractionComplete is linked to the slider's value. Notice how simple it is to achieve this powerful effect.

As you saw, the core logic is just one line: animator.fractionComplete = sender.value. This simple but powerful connection is the foundation of all interactive animations built with UIViewPropertyAnimator.


From Sliders to Gestures: Making it Truly Interactive

While a slider is a great way to understand the concept, real-world interactive animations are typically driven by gestures. The pattern for using a UIPanGestureRecognizer is a cornerstone of working with UIViewPropertyAnimator.

The "Building Better iOS App Animations" article you read earlier contains a perfect code snippet for this. Let's analyze it.

Building Better iOS App Animations

Let's revisit the article "Building Better iOS App Animations" to see how fractionComplete is used with a pan gesture.

First, review the code snippet under the section that begins "Let’s see how to use a UIPanGestureRecognizer...". Then, read the section "Step #2: Add a pan gesture." to see this pattern applied to a real example.

The logic breaks down elegantly based on the gesture's state:

  1. .began: The user touches down and starts panning.

    • Create the UIViewPropertyAnimator instance with the final state of the animation (e.g., the view's final position and alpha).
    • Crucially, you immediately call animator.pauseAnimation(). The animation is now in the active state but paused at the very beginning (fractionComplete is 0.0).
  2. .changed: The user drags their finger.

    • Calculate how far the user has dragged.
    • Convert that distance into a percentage (a value from 0.0 to 1.0).
    • Update animator.fractionComplete with this percentage. The UI will update instantly to match the animation's progress at that exact point.
  3. .ended: The user lifts their finger.

    • Call animator.continueAnimation(withTimingParameters: nil, durationFactor: 0). This tells the animator to complete the animation from its current progress to the end, using its original timing curve.

This pattern demonstrates the benefit of interruptibility. At any point during a "tap" animation, the user can touch down, "catch" the view mid-flight, and take control of its progress.


Beyond Scrubbing: Reversibility

Another powerful benefit is the ability to reverse an animation. Imagine a user starts to drag a panel open but changes their mind and flings it closed. You can use the gesture's velocity at the .ended state to decide whether to continue the animation or reverse it.

The same article you've been reading, "Building Better iOS App Animations," covers this in its section titled "Step #5: Use the pan velocity to reverse animations." (resource LINK). By checking recognizer.velocity(in: view) and setting transitionAnimator.isReversed = true, you can dynamically change the animation's direction. This creates a much more fluid and intuitive user experience.


Conclusion

In this lesson, we explored the "why" and "how" behind UIViewPropertyAnimator. You now understand its fundamental advantages over older animation APIs for creating modern, interactive user experiences.

Key Takeaways:

  • UIViewPropertyAnimator provides an object-oriented API for creating interactive, interruptible, and reversible animations.
  • It works by giving you an animator object that controls a Core Animation layer, allowing you to manipulate its progress.
  • The fractionComplete property is the key to interactivity, allowing you to drive an animation's progress from a user gesture or another external source.
  • A common pattern for gesture-driven animation is to pause() on .began, update fractionComplete on .changed, and continueAnimation() on .ended.

Preview of the Next Lesson:

We've covered the concepts and benefits today. In our next lesson, we'll put this knowledge into practice. You will implement an interactive animation driven by a pan gesture recognizer using UIViewPropertyAnimator, building a functional component from the ground up.