Awais Hussain Awais Hussain - 1 year ago 133
Objective-C Question

Exclude subviews from UIGestureRecognizer

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 Source

iOS 6 introduces a great new feature that solves this exact problem - a UIView (subview) can return NO from gestureRecognizerShouldBegin: (gesture recognizer attached to a superview). Indeed, that is the default for some UIView subclasses with regard to some gesture recognizers already (e.g. a UIButton with regard to a UITapGestureRecognizer attached to a superview).

See my book on this topic:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download