Monday, September 29, 2014

iOS Tutorial - Part 21 - Gestures

Gestures


Video Description 
If we want to recognize the user's touch events we have to use gesture recognizers. Events like pan, swipe, pinch ... are recognizable view UIGestureRecognizer class. We need to do the following steps for implementing Gestures.
1. Add the gesture recognizer to the view in order to recognize the gesture
2. Provide an implementation to handle the gesture
There are two approach in order to implement the above steps. First through the storyboard, second programatically. Lets start with the storyboard:

Add GestureRecognizer using Storyboard

1. From right bar side of Xcode in Object pallet, drag your desired gesture and drop it on the view that you want to implement the gesture.
2. Once you are done with the previous step, an icon will appear at the top of the view controller. If you go hover it, it will show the type of the gesture (e.g Swipe Gesture Recognizer). Control drag from this icon to your controller and make an IBAction. You can have your implementation inside of that method

Add GestureRecognizer programmatically

1. Create an outlet for the view that we want to have gesture for it, inside of it's controller. Control drag from your custom view to it's controller. If your view is created programmatically you don't need to create an outlet, just use the name of your view for next step.
2. Add the desired gesture recognizer to the outlet.
[self.yourCustomView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self.yourCustomView action:@selector(pan:)]]; 
3. Implement or handle the gesture inside of custom view class (not controller).

State property

Gesture recognizers have a property called "state" and it analyzes the current state of a touch. For example if user just started pan gesture, it's on the state "UIGestureRecognizerStateBegan". Another state is when the gesture is changing for example for pan, user dragging his finger on the screen and the position of his finger is changing. This state is called "UIGestureRecognizerStateChanged". When the gesture ends, the state will go to "UIGestureRecognizerStateEnded". The first two states are for the gestures that are continuous like pan and pinch. Gestures like tap and swipe doesn't have began and changed state, instead they have state called "UIGestureRecognizerStateRecognized". This state is for the time that device recognizes the gesture. If our gesture depends on the state of the gesture we can check by these properties.

Download

Download the Gesture App from here

No comments:

Post a Comment