Swipe Gesture iOS Tutorial

The iOS SDK can detect a number of gestures. In this tutorial we show how to detect the left and right swipe gesture. We will create a label which moves to the side of the swipe. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSSwipeGestureTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag a Label to the main view. Set the title of the Label to "Swipe" .Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Labe to the ViewController class and create the following Outlet

Change the viewDidLoad method to

override func viewDidLoad() {
    super.viewDidLoad()
        
    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
    let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes(_:)))
        
    leftSwipe.direction = .left
    rightSwipe.direction = .right

    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)
}

The Swipe Gesture Recognisers are defined and added to the view. When a gesture is detected the handleSwipes(_:) method is called, implement this method.

@objc func handleSwipes(_ sender:UISwipeGestureRecognizer) {
        
    if (sender.direction == .left) {
            print("Swipe Left")
        let labelPosition = CGPoint(x: swipeLabel.frame.origin.x - 50.0, y: swipeLabel.frame.origin.y)
        swipeLabel.frame = CGRect(x: labelPosition.x, y: labelPosition.y, width: swipeLabel.frame.size.width, height: swipeLabel.frame.size.height)
    }
        
    if (sender.direction == .right) {
        print("Swipe Right")
        let labelPosition = CGPoint(x: self.swipeLabel.frame.origin.x + 50.0, y: self.swipeLabel.frame.origin.y)
        swipeLabel.frame = CGRect(x: labelPosition.x, y: labelPosition.y, width: self.swipeLabel.frame.size.width, height: self.swipeLabel.frame.size.height)
    }
}

The direction of the swipe is checked, when a left swipe is detected the label moves left 50 points and with a right swipe it moves 50 points to the right. Build and Run the project and perform some swipes to move the label.

You can download the source code of the IOSSwipeGestureTutorial at the ioscreator repository on Github.