Detecting Long-Press Gestures in iOS 7

Gestures are a combination of touch events.  The most common gestures are built into the iOS SDK. In this tutorial we will detect a long-press gesture and display an alert view.

Update: Dec 7, 2014. The rewritten version in Swift for iOS 8 and Xcode 6 is available here.

Open Xcode and create a new Single View Application. For product name, use iOS7LongPressGestureTutorial and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices.

Go to the Storyboard and drag a button to the main View. Give them a title of "Press me". The storyboard should look like this.

Add the following property in ViewController.m

@property (nonatomic,strong) UILongPressGestureRecognizer *lpgr;

Add the following lines to the viewDidLoad method

self.lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGestures:)];
self.lpgr.minimumPressDuration = 1.0f;
self.lpgr.allowableMovement = 100.0f;

[self.view addGestureRecognizer:self.lpgr];

We initialize the LongPressGesture with a selector method which we will implement next. The minimum press duration is 1 second and no more than 100 points may be moved when the long-press gesture is started. Next, implement the handleLongPressGestures method.

- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)sender
if ([sender isEqual:self.lpgr]) {
if (sender.state == UIGestureRecognizerStateBegan)
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Gestures" message:@"Long Gesture Detected" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];

When the long-press is started the state of the gesture changes in UIGestureRecognizerStateBegan. This is also needed to keep track of multiple long presses. When the press is long enough, in our case 1 second, an Alert View will be displayed. Build and Run, and long-press the button to display the Alert View.

You can download the source code of the iOS7LongPressGestureTutorial at the ioscreator repository on github.