Friday, 10 April 2015

Gesture Recognition in iOS

Overview

In iOS 3.0, Apple introduce new UIGestureRecognizer Class! These provide a default implementation of detecting common gestures such as taps, pinches, rotations, swipes, pans, and long presses.
Gesture recognizers convert low-level event handling code into higher-level actions. They are objects that  attach to a view, which allows the view to respond to actions the way a control does. If they recognize their assigned gesture, they send an action message to a target object. The target object is typically the view’s view controller, which responds to the gesture.

A view can have with multiple Gesture Recognitions but a  Gesture Recognizer can't associate with multiple views.

Gesture Recognizer classes of the UIKit framework
  • Tap (any number of taps) = UITapGestureRecognizer
  • Pinch  (for zooming)         = UIPinchGestureRecognizer
  • Pan or Drag                      = UIPanGestureRecognizer
  • Swipe (any direction)        =  UISwipeGestureRecognizer
  • Rotating                            =  UIrotationGestureRecognizer
  • Long Press                       =  UILongPressGestureRecognizer

UITapGestureRecognizer:

UITapGestureRecognizer is sub class of UIGestureRecognizer that look for single and multiple taps on associated view.
Adding UITapGestureRecognizer to a view.
1) Creating a Gesture Recognition: You can create a Gesture Recognition by specifying a callback method  so the Gesture Recognition send you update when gesture starts, changes, or ends.
2)Add Gesture Recognition to View : Each gesture is associated with one view.When a touch occurs within the bounds of that view, the gesture recognizer see if it matches the type of touch it’s looking for, and if a match is found it will notify the callback method.

Example:
Adding a Tap Gesture Recognizer to a View:

CallBack method for Gesture Recognizer:

-(void) handleTapGestureRecognizer:(id) sender{
       NSLog("Tap Gesture Occurred");
}

Adding Gesture to view
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer:)];
tapGesture.numberOfTapsRequired = 2;    //Default is 1.
[view addGestureRecognizer:tapGesture];

Note: userInteractionEnabled is always "YES" for specified view.

In the same way you can use rest of Gesture Recognizers.















No comments:

Post a Comment