UIKit Dynamics in the real world

Swiping right on simpler code 😏

UIDynamics have been available since iOS 7, and its a very powerful tool that allow us to create complex interactions pretty simply. For example, the iPad’s Picture on Picture feature is done using UIFieldBehavior , maybe we will cover that in another article.

In this article we will explore recreating the famous but yet overused Tinder UI. There are tons of libraries out there that provide this functionality, but they are all based on some really complex logic around moving the views and then resetting them into their original position. Hundreds of lines of code later we have something similar to Tinder, but it doesn’t seem right. We can do something way simpler.

You can download the final project on GitHub.

Enter UIDynamicAnimator

The definition of UIDynamicAnimator is very straightforward, it reads:

An object that provides physics-related capabilities and animations for its dynamic items, and provides the context for those animations.

By using physics as the constraints you apply to your views UIDynamic is able to calculate and animate them accordingly. We will use this to our advantage when recreating the Tinder swipe animation.

Breaking down the Tinder UI into physics, leaves us with only two items: cards snap back into position if let go, and cards can be push around with your fingers using force. The latter is a simple UIPanGestureRecognizer , for the former we need to talk a bit about UIDynamicBehavior .

Applying rules to the animator with UIDynamicBehavior

Behaviours are the iOS provided way to tell a view (an UIDynamicItem ) how to perform its physics based animations. At the moment of this writing there are several of them

That last one looks really suspicious, an UISnapBehavior is exactly what we discussed before about how the Tinder card effect works. That was our last piece of the puzzle, we can jump into some code now.

Panning a view around the screen

The first step in order to achieve the effect is to allow users to drag the view with their fingers. This can be achieved using several techniques, we will focus on our old friend UIPanGestureRecognizer, and it looks something like this.