I'm trying to figure out how this is done the right way. I've tried to depict the situation:
I'm adding a UITableView
as a subview of a UIView
. The UIView
responds to a tap- and pinchGestureRecognizer
, but when doing so, the tableview stops reacting to those two gestures (it still reacts to swipes).
I've made it work with the following code, but it's obviously not a nice solution and I'm sure there is a better way. This is put in the UIView
(the superview):
-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
if([super hitTest:point withEvent:event] == self) {
for (id gesture in self.gestureRecognizers) {
[gesture setEnabled:YES];
}
return self;
}
for (id gesture in self.gestureRecognizers) {
[gesture setEnabled:NO];
}
return [self.subviews lastObject];
}
I was displaying a dropdown subview that had its own tableview. As a result, the
touch.view
would sometimes return classes likeUITableViewCell
. I had to step through the superclass(es) to ensure it was the subclass I thought it was:I had a very similar problem and found my solution in this SO question. In summary, set yourself as the delegate for your
UIGestureRecognizer
and then check the targeted view before allowing your recognizer to process the touch. The relevant delegate method is:It is possible to do without inherit any class.
you can check gestureRecognizers in gesture's callback selector
if view.gestureRecognizers not contains your gestureRecognizer,just ignore it
for example
check view.gestureRecognizers here
Building on @Pin Shih Wang answer. We ignore all taps other than those on the view containing the tap gesture recognizer. All taps are forwarded to the view hierarchy as normal as we've set
tapGestureRecognizer.cancelsTouchesInView = false
. Here is the code in Swift3/4:One possibility is to subclass your gesture recognizer (if you haven't already) and override
-touchesBegan:withEvent:
such that it determines whether each touch began in an excluded subview and calls-ignoreTouch:forEvent:
for that touch if it did.Obviously, you'll also need to add a property to keep track of the excluded subview, or perhaps better, an array of excluded subviews.
I was also doing a popover and this is how I did it