Getting the UITouch objects for a UIGestureRecognizer

Morrowless picture Morrowless · Dec 15, 2010 · Viewed 21.5k times · Source

Is there a way to get the UITouch objects associated with a gesture? UIGestureRecognizer doesn't seem to have any methods for this.

Answer

wpearse picture wpearse · Dec 16, 2010

Jay's right... you'll want a subclass. Try this one for size, it's from one of my projects. In DragGestureRecognizer.h:

@interface DragGestureRecognizer : UILongPressGestureRecognizer {

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

@end

@protocol DragGestureRecognizerDelegate <UIGestureRecognizerDelegate>
- (void) gestureRecognizer:(UIGestureRecognizer *)gr movedWithTouches:(NSSet*)touches andEvent:(UIEvent *)event;
@end

And in DragGestureRecognizer.m:

#import "DragGestureRecognizer.h"


@implementation DragGestureRecognizer

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    [super touchesMoved:touches withEvent:event];

    if ([self.delegate respondsToSelector:@selector(gestureRecognizer:movedWithTouches:andEvent:)]) {
        [(id)self.delegate gestureRecognizer:self movedWithTouches:touches andEvent:event];
    }

}

@end 

Of course, you'll need to implement the

- (void) gestureRecognizer:(UIGestureRecognizer *)gr movedWithTouches:(NSSet*)touches andEvent:(UIEvent *)event; 

method in your delegate -- for example:

DragGestureRecognizer * gr = [[DragGestureRecognizer alloc] initWithTarget:self action:@selector(pressed:)];
gr.minimumPressDuration = 0.15;
gr.delegate = self;
[self.view addGestureRecognizer:gr];
[gr release];



- (void) gestureRecognizer:(UIGestureRecognizer *)gr movedWithTouches:(NSSet*)touches andEvent:(UIEvent *)event{

    UITouch * touch = [touches anyObject];
    self.mTouchPoint = [touch locationInView:self.view];
    self.mFingerCount = [touches count];

}