Search code examples
iphonexcodeuiwebviewgestures

How to allow UITapGestureRecognizer to detect taps on web view?


I have made web browser for iPhone in Xcode, and to exit the web browser and go back to the main page you tap on the screen three times, except that the gesture will only work on the toolbars at the top and bottom of the screen but not on the web view.

What can I do?

Here is my code

.h File

#import <UIKit/UIKit.h>

@interface Internet : UIViewController {


IBOutlet UIWebView *webview;
IBOutlet UIBarButtonItem *forwards;
IBOutlet UIBarButtonItem *backwards;
IBOutlet UITextField *URLTextField;

}

- (IBAction)share:(id)sender;

- (IBAction)returnKeyPressed:(id)sender;
- (IBAction)google:(id)sender;
- (IBAction)reload:(id)sender;
- (IBAction)forwardsButton:(id)sender;
- (IBAction)backwardsButton:(id)sender;



@end

.m File (only relevant code shown)

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    NSString *homePageString = @"http://www.google.com";
    NSURL *homePage = [NSURL URLWithString:homePageString];
    NSURLRequest *requestHomePage = [NSURLRequest requestWithURL:homePage];
    [webview loadRequest:requestHomePage];
    forwards.enabled = NO;
    backwards.enabled = NO;
    UIAlertView *touchHelp = [[UIAlertView alloc] initWithTitle:@"Alert, Please Read" message:@"To go back to the App Selection Page please anywhere on the top or bottom toolbar three times" delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
    [touchHelp show];
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
    tapRecognizer.numberOfTapsRequired = 3;
    [self.view addGestureRecognizer:tapRecognizer];
}

- (void)tapDetected:(UITapGestureRecognizer *)tapRecognizer {
    [self dismissViewControllerAnimated:YES completion:nil];
}

Solution

  • Implement shouldRecognizeSimultaneouslyWithGestureRecognizer delegate and return YES.

    Implementation details:

    Add the UIGestureRecognizerDelegate protocol to your .h file

    @interface ViewController : UIViewController <UIGestureRecognizerDelegate>
    

    Add this delegate in your .m file

    -(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer 
     {
        return YES
     }