Detecting Swipe Gestures in iOS8 with Swift

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 built with Xcode 6.1 and built for iOS8.1

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftSwipeGestureTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

o to the Storyboard and drag a label from the Object Library to the main View.

Select the Assistant Editor and open ViewController.swift. Ctrl and drag from the Label to the ViewController.swift and create the following Outlet.

In ViewController.swift change the viewDidLoad method to

override func viewDidLoad() {
    super.viewDidLoad()
    
    var leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
    var rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipes:"))
    
    leftSwipe.direction = .Left
    rightSwipe.direction = .Right
    
    view.addGestureRecognizer(leftSwipe)
    view.addGestureRecognizer(rightSwipe)
  }

he Swipe Gesture Recognisers are defined and added to the view. When a gesture is detected the HandleSwipes method is called, implement this method.

func handleSwipes(sender:UISwipeGestureRecognizer) {
    if (sender.direction == .Left) {
      println("Swipe Left")
      var labelPosition = CGPointMake(self.swipeLabel.frame.origin.x - 50.0, self.swipeLabel.frame.origin.y);
      swipeLabel.frame = CGRectMake( labelPosition.x , labelPosition.y , self.swipeLabel.frame.size.width, self.swipeLabel.frame.size.height)
    }
    
    if (sender.direction == .Right) {
      println("Swipe Right")
      var labelPosition = CGPointMake(self.swipeLabel.frame.origin.x + 50.0, self.swipeLabel.frame.origin.y);
      swipeLabel.frame = CGRectMake( labelPosition.x , labelPosition.y , self.swipeLabel.frame.size.width, 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 iOS8SwiftSwipeGestureTutorial at the ioscreator repository on github.