O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

8.4. Detecting Long Press Gestures

Problem

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

Solution

Create an instance of the UILongPressGestureRecognizer class and add it to the view that has to detect long tap gestures. The .h file of the view controller is defined in this way:

#import <UIKit/UIKit.h>

@interface Detecting_Long_Press_GesturesViewController : UIViewController

@property (nonatomic, strong)
  UILongPressGestureRecognizer *longPressGestureRecognizer;

@property (nonatomic, strong) UIButton *dummyButton;

@end

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.view.backgroundColor = [UIColor whiteColor];
  
  self.dummyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  self.dummyButton.frame = CGRectMake(0.0f,
                                      0.0f, 
                                      72.0f,
                                      37.0f);
  self.dummyButton.center = self.view.center;
  [self.view addSubview:self.dummyButton];
  
  /* First create the gesture recognizer */
  self.longPressGestureRecognizer = 
  [[UILongPressGestureRecognizer alloc] 
   initWithTarget:self
   action:@selector(handleLongPressGestures:)];
  
  /* 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 two fingers ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required