Implementing gestures in SwiftUI

Alexander Ershov
2 min readNov 23, 2019

--

To handle gestures SwiftUI has Gesture protocol. Currently, there are 5 implementations of the protocol. Let explore all of them!

Let’s start from a simple tap gesture. It can be handled by TapGesture. Let’s create a simple rounded rectangle that can change his color after each tap. You can see the example below. 😉

So, its time to dive into the implementation:

After a simple tap, we are going to implement a long tap. To handle it we will use LongPressGesture. Now we will change the rectangle’s color only if the tap takes at least 2 seconds. Let’s see how it can be implemented 👇

So, after taps, we can try to drag our rectangle. DragGesture will help us to make it work! You can see the example and the implementation below.

So far, we have studied only one-hand gestures and now it’s time to study two-hand ones. The first one is the magnification gesture. You can see how it works on the example. To implement it we will use MagnificationGesture

And the last one is the rotation. It can be handled by RotationGesture. Now our rectangle rotates 🙃

That’s all ;)

We studied all types of default gestures in SwiftUI. But if you want to explore them more you can read the official documentation.

P.S. you can contact me via Twitter or LinkedIn 😉

--

--