24

In iOS, is it possible to put a tap recognizer on a UIWebView, so that when someone single-taps the web view, an action gets performed?

Code below doesn't seem fire handleTap when I tap my webView.

Thanks.

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self 
                                                                      action:@selector(handleTap)];
tap.numberOfTapsRequired = 1;

[webView addGestureRecognizer:tap];
[tap release]; 


-(void) handleTap {
    NSLog(@"tap");
}
Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
user768339
  • 603
  • 2
  • 7
  • 8

3 Answers3

42

I found that I had to implement this method to get it to work:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}
Bryan
  • 11,398
  • 3
  • 53
  • 78
  • I found that this is not needed when the web view is displaying a PDF document, but it is needed when displaying a text, HTML or image document. – arlomedia Jul 17 '12 at 17:13
  • With the same code. it run for some first time then did not run! – dellos May 21 '17 at 08:58
24

Your UIViewController subclass should implement UIGestureRecognizerDelegate and return YES from gestureRecognizer: shouldReceiveTouch: when appropriate.

Then you can assign it to the delegate property of your UIGestureRecognizer.

tap.delegate = self;
highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
10
  1. Add UIGestureRecognizerDelegate to view controller

    <UIGestureRecognizerDelegate>
    
  2. Add Tap Gesture to Webview.

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(flip)];
    tap.numberOfTapsRequired = 1;
    tap.delegate = self;
    [_webview addGestureRecognizer:tap];
    
  3. - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer    shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
        return YES;
    }
    
Kiran S
  • 403
  • 8
  • 13
  • This is the most complete answer. You don’t need tap.numberOfTapsRequired since the default is 1. – JScarry Mar 24 '15 at 22:06