iOS Gesture Handling

 

Handle Gesture

To handle an iOS gesture

  • Adding a gesture recognizer to a view to recognize a gesture
  • Implement the gesture handler for a view inside a view controller
    MyViewController.m
    - (void)viewDidLoad
    {
            ...
    	[super viewDidLoad];
    	UIGestureRecognizer *gesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self.myView
                                                            action:@selector(pinch:)];
    	[self.myView addGestureRecognizer:gesture];
            ...
    }
    
  • Create a gesture action handler: Use the View myView's pinch method to handle the pinch gesture
  • Add the gesture action handler to handle the view gesture
- (void)viewDidLoad
{
  UISwipeGestureRecognizer *swipeGR = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipe)];
  swipeGR.direction = UISwipeGestureRecognizerDirectionUp;
  [self.view addGestureRecognizer:swipeGR];

  UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
  [self.view addGestureRecognizer:tapGR];
}

Implement the Gesture action handler

MyView.m
- (void)pinch:(UIPinchGestureRecognizer *)gesture
{
	if ((gesture.state == UIGestureRecognizerStateChanged) ||
	    (gesture.state == UIGestureRecognizerStateEnded)) {
           ...
           gesture.scale = 1;
	}
}
  • gesture provides details on the gesture
  • Reset the gesture to the default value after handling the action
               gesture.scale = 1;
    
    

UIPanGestureRecognizer provides the following specific methods to access/reset gesture information

- (CGPoint)translationInView:(UIView *)aView;
- (CGPoint)velocityInView:(UIView *)aView;
- (void)setTranslation:(CGPoint)translation inView:(UIView *)aView;

Handle a pan event

- (void)pan:(UIPabGestureRecognizer *)gesture
{
	if ((gesture.state == UIGestureRecognizerStateChanged) ||
	    (gesture.state == UIGestureRecognizerStateEnded)) {

            CGPoint translation = [recognizer translationInView:self];
            CGPointMake(self.origin.x+translation.x, self.origin.y+translation.y);
            [recognizer setTranslation:CGPointZero inView:self];
        }
}
  • translation: how much the gesture move
        [recognizer setTranslation:CGPointZero inView:self]
    
  • Reset the translation to zero once handling the event

UIPinchGestureRecognizer

Support properties

@property CGFloat scale;
@property (readonly) CGFloat velocity;

UIRotationGestureRecognizer

Support properties

@property CGFloat rotation;
@property (readonly) CGFloat velocity;

UISwipeGestureRecognizer

Support properties

@property UISwipeGestureRecognizerDirection direction; //what direction
@property NSUInteger numberOfTouchesRequired; // Number of tap finger

UITapGestureRecognizer

Support properties

@property NSUInteger numberOfTapsRequired;
@property NSUInteger numberOfTouchesRequired;