Detecting Long-Press Gestures Tutorial in iOS8 with Swift

Long-press gestures is a  type of a continuous gesture. The SDK will detect if a press is pushed long instead of a single tap. In this tutorial we will detect a long-press gesture and display an alert view. This tutorial is built in iOS 8.1 and Xcode 6.1

Update: Aug 24, 2017. The rewritten version in Swift 4 for iOS 11 and Xcode 9 is available here.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftLongPressGesturesTutorial 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 Button from the Object Library to the View Controller. Change the title of the Button to "Press Me". Also change the background color of the main view to light-gray. Select the button select the "Resolve Auto Layout Issues" button at the bottom-right(3rd button) and select Add Missing Constraints.

Drag a Long Press Gesture Recognizer from the Object Library on top of the Button. The Storyboard should look like this.

elect the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Long Press Gesture Recognizer to the ViewController class  and create the following Action.

Go to the ViewController.swift file and implement the handleGesture method

@IBAction func handleGesture(sender: AnyObject) {
    if sender.state == UIGestureRecognizerState.Began
      let alertController = UIAlertController(title: nil, message:
        "Long-Press Gesture Detected", preferredStyle: UIAlertControllerStyle.Alert)
      alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
      self.presentViewController(alertController, animated: true, completion: nil)

The Began UIRecognizerState is a continuous state. If this is recognised an Alert View is Presented. Build and Run the project and press long on the Button.

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