frangulyan
frangulyan

Reputation: 3867

iOS tap recognizer to catch all taps

I want a pretty simple thing - in my top controller (which is navigation controller) to set up a tap gesture recognizer which will catch all the taps everywhere on the view. Currently when I tap on a button the system is not even thinking to bother my recognizer (except the gestureRecognizer:shouldReceiveTouch: delegate method, where I return YES). Instead, it just executes a button click. So I want to install "the strongest" recognizer on a view hierarchy no matter what.

Upvotes: 0

Views: 1541

Answers (1)

EricS
EricS

Reputation: 9768

You might try putting an empty UIView on top of all other views and add the UITapGestureRecognizer to it. We do something similar with help overlays. The biggest issue is figuring out how and when to ignore the touches so the underlying buttons get them when needed.

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *b = [UIButton buttonWithType:UIButtonTypeInfoDark];
    b.frame = CGRectMake(50,50, b.bounds.size.width, b.bounds.size.height );
    [self.view addSubview:b];

    UIView *invisibleView = [[UIView alloc] initWithFrame:self.view.bounds];
    invisibleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [invisibleView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHit:)]];
    [self.view addSubview:invisibleView];
}

-(void)tapHit:(UITapGestureRecognizer*)tap {
    NSLog( @"tapHit" );
}
@end

Upvotes: 1

Related Questions