user805627
user805627

Reputation: 4417

How to prevent a tap event delivered to superview?

There is a UIView named viewA, viewA has a UITapGestureRecognizer, I can't modify the recognizer's target code.
And viewA has many subviews. For some specific subviews, I want they don't deliver tap event to viewA when I touch them (for other subviews, they should deliver tap event to viewA). What should I do?

Upvotes: 3

Views: 2883

Answers (3)

PakitoV
PakitoV

Reputation: 2498

You can have an array with the views you want to avoid reacting to touch:

NSArray <UIView *> *untouchableSubviews; //will contain the views you don't want to touch

and override the hitTest in your container view (viewA in your case)

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *view = [super hitTest:point withEvent:event];
    if ([_untouchableViews containsObject:view]) {
        return nil; //this view will pass touch events to his superview
    }
    else{
        return view; //this view will handle touch events itself
    }
}

Upvotes: 0

tiltem
tiltem

Reputation: 5032

Set viewA as delegate of recognizer. then use delegate method:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch

check if touch is in unwanted subviews:

for(UIView *v in unwantedSubviewsArray){
    CGPoint touchLocation = [touch locationInView:v];
    if (CGRectContainsPoint(v.frame, touchLocation)){
        return NO;
    }
}
return YES;

Upvotes: 1

Felix
Felix

Reputation: 35384

Add another UITapGestureRecognizer to these subviews, so the taps won't be delivered to the superview.

Upvotes: 1

Related Questions