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 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11SwipeGestureTutorial 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 Labelthe main view. Set the title of the Labe to ".Swipe" .Select the Button and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Button and select the Auto Layout pin button. Pin the Button to the top and and click "Add 1 Constraint".

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

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: 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)
    }
        
    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.

Build and Run the project.

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