How to detect swipe vertically on a ScrollView using Swift?

iOSiPhone/iPadMobile DevelopmentSwift

To detect swipe in scrollView we will need to make use of some tricks as scroll view does not natively give the directions of scroll made on it. We’ll see this with help of an example.

Create an empty project, add scroll view to the view as per your requirement.

Give them constraint as required in the application.

From the object library, drag and drop a swipe gesture recognizer right above the Scroll View.

Select the gesture recognizer, go to its attribute inspector and from there, select the swipe option and set the value as “up”.

When you do this, now your gesture recognizer can recognize up swipes only. Now you need to create a method for this swipe gesture.

@IBAction func swipeMade(_ sender: UISwipeGestureRecognizer) {
   if sender.direction == .up {
      print("up swipe made")
      // perform actions here.
   }
}

When you write this code, the recognizer sends events to this method, and if the swipe direction is up, it will come inside the if block. You can perform your desired operation here.

When we run this code on a device and make a swipe, below is the result that’s produced on the console.

raja
Updated on 30-Jul-2019 22:30:24

Advertisements