10.4. Detecting Long-Press Gestures


You want to be able to detect when the user taps and holds his finger on a view for a certain period of time.


Create an instance of the UILongPressGestureRecognizer class and add it to the view that has to detect long-tap gestures:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong)
    UILongPressGestureRecognizer *longPressGestureRecognizer;
@property (nonatomic, strong) UIButton *dummyButton;

@implementation ViewController

Here is the viewDidLoad instance method of the view controller that uses the long-press gesture recognizer that we defined in the .m file:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dummyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    self.dummyButton.frame = CGRectMake(0.0f,
    [self.dummyButton setTitle:@"My button" forState:UIControlStateNormal];
    self.dummyButton.center = self.view.center;
    [self.view addSubview:self.dummyButton];
    /* First create the gesture recognizer */
    self.longPressGestureRecognizer =
    [[UILongPressGestureRecognizer alloc]
    /* The number of fingers that must be present on the screen */
    self.longPressGestureRecognizer.numberOfTouchesRequired = 2;
    /* Maximum 100 points of movement allowed before the gesture
     is recognized */
    self.longPressGestureRecognizer.allowableMovement = 100.0f;
    /* The user must press 2 fingers (numberOfTouchesRequired) for
 at least 1 second ...

Get iOS 7 Programming Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.