7.6. Detecting Pinch Gestures

Problem

You want your users to be able to perform a pinch gesture on a view.

Solution

Create an instance of the UIPinchGestureRecognizer class and add it to your target view, using the addGestureRecognizer: instance method of the UIView class:

- (void)viewDidLoad {
  [super viewDidLoad];
  
  self.view.backgroundColor = [UIColor whiteColor];
  
  CGRect labelRect = CGRectMake(0.0f,     /* X */
                                0.0f,     /* Y */
                                200.0f,   /* Width */
                                200.0f);  /* Height */  
  
  self.myBlackLabel = [[UILabel alloc] initWithFrame:labelRect];
  self.myBlackLabel.center = self.view.center;
  self.myBlackLabel.backgroundColor = [UIColor blackColor];
  
  /* Without this line, the pinch gesture recognizer
   will not work */
  self.myBlackLabel.userInteractionEnabled = YES;
  [self.view addSubview:self.myBlackLabel];
  
  /* Create the Pinch Gesture Recognizer */
  self.pinchGestureRecognizer =  [[UIPinchGestureRecognizer alloc] 
                                  initWithTarget:self
                                  action:@selector(handlePinches:)];
  
  /* Add this gesture recognizer to the view */
  [self.myBlackLabel 
   addGestureRecognizer:self.pinchGestureRecognizer];
  
}

- (void) viewDidUnload{
  [super viewDidUnload];
  self.myBlackLabel = nil;
  self.pinchGestureRecognizer = nil;
}

The .h file of the view controller is defined in this way:

#import <UIKit/UIKit.h> @interface Detecting_Pinch_GesturesViewController : UIViewController @property (nonatomic, strong) UIPinchGestureRecognizer *pinchGestureRecognizer; @property (nonatomic, strong) UILabel *myBlackLabel; @property (nonatomic, unsafe_unretained) CGFloat ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.