Can you attach a UIGestureRecognizer to multiple views?
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 objectusing 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]; ....}
For Swift 3 in case anyone requires this:Based on Bhavik Rathod Answer above.
func setGestureRecognizer() -> UIPanGestureRecognizer { var panRecognizer = UIPanGestureRecognizer() panRecognizer = UIPanGestureRecognizer (target: self, action: #selector(pan(panGesture:))) panRecognizer.minimumNumberOfTouches = 1 panRecognizer.maximumNumberOfTouches = 1 return panRecognizer } ///set the recognize in multiple views view1.addGestureRecognizer(setGestureRecognizer()) view2.addGestureRecognizer(setGestureRecognizer())