Gesture Recognizers
Writing and maintaining a state machine that interprets touches across a combination of three or four touches...
methods is hard enough when a view confines itself to expecting only one kind of gesture, such as dragging. It becomes even more involved when a view wants to accept and respond differently to different kinds of gesture. This was a serious problem for developers up through version 3.1.3 of the system, and it was compounded by the fact that users were becoming accustomed to a vocabulary of basic gestures that every developer had to implement independently.
In iOS 3.2, Apple took a major step toward alleviating these difficulties by introducing gesture recognizers, which standardize common gestures and allow the code for different gestures to be separated and encapsulated into different objects.
Distinguishing Gestures Manually
To see the value of gesture recognizers, it will help to try first to write code that differentiates gestures without them.
Imagine first a view that distinguishes between a finger tapping briefly and a finger remaining down for a longer time. We can’t know how long a tap is until it’s over, so one approach might be to wait until then before deciding:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { self->time = [[touches anyObject] timestamp]; } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { NSTimeInterval diff = event.timestamp - self->time; if (diff < 0.4) NSLog(@"short"); else NSLog(@"long"); ...
Get Programming iOS 4 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.