I have multiple views defined in my main view. I want to add single tap gesture to all these views. Below is the code I have written, but this registers a tap gesture to the last view that I add. So in the code below, tap is registered only for messagesView
& not for other views. I have 2 questions:
How do I register the same tapGesture to multiple Views?
Lets assume I get this working, now all single taps from these views goto the same function called
oneTap
. In this function how do I distinguish from which view the tap is coming?
Code:
@synthesize feedsView, peopleView, messagesView, photosView;
- (void)viewDidLoad
{
[super viewDidLoad];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneTap:)];
[singleTap setNumberOfTapsRequired:1];
[singleTap setNumberOfTouchesRequired:1];
[feedsView addGestureRecognizer:singleTap];
[peopleView addGestureRecognizer:singleTap];
[messagesView addGestureRecognizer:singleTap];
//[photosView addGestureRecognizer:singleTap];
[singleTap release];
return;
}
I had the same problem where it only added to the last view. There might be a better solution, but I just created a tag gesture for each view and linked them to the same selector method (
oneTap:
in your case). In order to distinguish which view activated the method, you can just tag your views,feedsView.tag = 0; peopleView.tag = 1;
and so on. Then when the method is called:// Add tap gesture in swift 4
//USE in view did load: tapGestures(view: view1) tapGestures(view: view2) tapGestures(view: view3)
1 use hitTest:
2 add THE Single TapGesture to multi views, only last view worked.
Can you attach a UIGestureRecognizer to multiple views? No.
Two options:
a) Give every
UIGestureRecognizer
its own action. Pluses of this approach: strong decoupling. Minuses: more code reuse. But, you can mitigate code reuse by creating methods for common functionalities and just call the methods in the different actions.b) Give every view to which you add a
UIGestureRecognizer
a unique tag. Then, use a switch statement in the common action with the sender's view's tag as the case. Pluses: less code reuse. Minuses: tighter coupling. Something like this:Then:
Although it's usually best to go with the option that decouples, if all of your actions are very similar, which seems to be the case here, and you are quite sure that they'll remain very similar in the future, then option b) with the tags is probably the better choice.
P.S. It's unnecessary to explicitly set
numberOfTapsRequired
&numberOfTouchesRequired
to1
since they're both set to1
by default. You can confirm this by holding Command and clicking onnumberOfTapsRequired
in Xcode.