This question already has an answer here:
I am working on a sample of Pan Gesture. I am keen to know that can I add single gesture on two views?
My code is as follows:
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(invokePanGesture:)];
[panGesture setMinimumNumberOfTouches:1];
[panGesture setMaximumNumberOfTouches:2];
[btnGreen addGestureRecognizer:panGesture];
[btnYellow addGestureRecognizer:panGesture];
my handler method is as follows:
- (void)invokePanGesture:(UIPanGestureRecognizer*)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}
The problem now is gesture recognizer is considering only last view in my case btnYellow
as its view. If I create two separate GestureRecognizer object it works. So please clear me that:
Is it possible to have single gesture in multiple views or not?
If yes then how?
If now then why?
Thanks in Advance
Can't you just write your invokePanGesture method to do the same thing to both views at the same time?
I don't think it's possible.
Please have a look at https://stackoverflow.com/a/5567684/470964.
Also https://stackoverflow.com/a/7883902/470964: Maybe it's also a solution for your problem. I think the answer is that the GestureRecognizer has only one view property, that will be set.
From the docs for UIGestureRecognizer
A gesture recognizer operates on touches hit-tested to a specific view and all of that view’s subviews. It thus must be associated with that view. To make that association you must call the UIView method addGestureRecognizer:. A gesture recognizer does not participate in the view’s responder chain.
So, in summary the only way a GestureRecognizer can operate on more than one view is if the recognizer operates on a superview of the other views.