How to handle right-to-left and left-to-right swipe gestures on iOS App?

To handle gestures in iOS application we’ll create an application with swift and see with help of an example. This can be done in two ways, with storyboard or programmatically.

Method 1 − With storyboard

First we’ll drag a swipe gesture recognizer from our object library and drop it in our View controller in which we want to add the swipe gesture.

Then click on the gesture, press control and drag in your view controller class to create its connection.

Make sure the sender of that action is UISwipeGestureRecognizer and the action looks something like this:

@IBAction func swipeMade(_ sender: UISwipeGestureRecognizer) { }

Now the swipe gesture in iOS provides the direction of the swipe made inside its property direction. The direction is an enum which has these possible values.

  • Right
  • Left
  • Down
  • Up

The swipe gesture can only handle swipe in only one direction, either left, right, up or down. So we need to create another swipe gesture recognizer and from the attribute inspector set its direction to left.

Also remember to connect the action of new recognizer to the action for our first recognizer.

Now we’ll use this method along with direction property to handle the swipes made. Apart from doing it from the storyboard, we can also do it programmatically.

Method 2 − Programmatically

To programmatically create gesture recognizers we’ll have to add the following code to our viewDidLoad.

var leftRecognizer = UISwipeGestureRecognizer(target: self, action:
   leftRecognizer.direction = .left
var rightRecognizer = UISwipeGestureRecognizer(target: self, action:
   rightRecognizer.direction = .right

In both the methods of doing this, the swipeMade action shown below should remain the same.

@IBAction func swipeMade(_ sender: UISwipeGestureRecognizer) {
   if sender.direction == .left {
      print("left swipe made")
   if sender.direction == .right {
      print("right swipe made")

When we run this application on our device, we don’t see any interface as our view is empty at this time but when we swipe left or right we get an output in the console which shows that a swipe was made in either direction.

Updated on: 30-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started