Exclude subviews from UIGestureRecognizer

Awais Hussain picture Awais Hussain · Mar 17, 2013 · Viewed 17.5k times · Source

I have a UIView (the 'container view') which contains several 'sub views'. I want to add a UITapGestureRecognizer to the container view, such that it is activated when I touch the region inside the container view but outside the subviews.

At the moment, touching anywhere inside the container view, including inside the subviews activates the gesture recognizer.

The implementation looks something like this: In the controller:

ContainerView *containerView = [[ContainerView alloc] initWithSubViews:array];
UITapGestureRecognizer *tap = [UITapGestureRecognizer alloc] initWithTarget:self action:@selector(someSelector)];
[containerView addGestureRecognizer:tap];
[self.view addSubView:containerView];

In ContainerView.m

-(id)initWithSubviews:(NSArray *)array {
    for (subView *s in array) {
        [self addSubView:s];
    }
    return self;
}

I think the problem occurs because the gesture recognizer is added after the subviews are. If that is true then the solution would require breaking the initWithSubViews method into two separate ones, which I would prefer to avoid.

Thank You

Answer

vietstone picture vietstone · Sep 19, 2013

I used the simple way below. It works perpectly!

Implement UIGestureRecognizerDelegate function, accept only touchs on superview, not accept touchs on subviews:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view != _mySuperView) { // accept only touchs on superview, not accept touchs on subviews
        return NO;
    }

    return YES;
}