Can you attach a UIGestureRecognizer to multiple views?
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTapTap:)];
[self.view1 addGestureRecognizer:tapGesture];
[self.view2 addGestureRecognizer:tapGesture];
[tapGesture release];
In the above code only taps on view2
are recognized. If I comment out the third line then taps on view1
are recognized. If I'm right and you can only use a gesture recognizer once, I'm not sure if this is a bug or it just needs some more documentation.
A UIGestureRecognizer
is to be used with a single view. I agree the documentation is spotty. That UIGestureRecognizer
has a single view
property gives it away:
view
The view the gesture recognizer is attached to. (read-only)
@property(nonatomic, readonly) UIView *view
Discussion You attach (or add) a gesture recognizer to a UIView object using the addGestureRecognizer: method.
I got around it by using the below.
for (UIButton *aButton in myButtons) {
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
longPress.minimumPressDuration=1.0;
[aButton addGestureRecognizer:longPress];
[longPress release];
}
Then in my handleLongPress method I just set a UIButton equal to the view of the gesture recognizer and branch what I do based upon that button
- (void)handleLongPress:(UILongPressGestureRecognizer*)gesture {
if ( gesture.state == UIGestureRecognizerStateEnded ) {
UIButton *whichButton=(UIButton *)[gesture view];
selectedButton=(UIButton *)[gesture view];
....
}