O'Reilly logo

iOS 5 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

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 ...

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