Handling touches inside UIWebview

I have created a subclass of UIWebView , and have implemented the touchesBegan, touchesMoved and touchesEnded methods.

but the webview subclass is not handling the touch events.

Is there any method to handle the touch events inside the UIWebView subclass ???


Solution 1:

No subclassing needed, just add a UITapGestureRecognizer :

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapMethod)];
[tap setNumberOfTapsRequired:1]; // Set your own number here
[tap setDelegate:self]; // Add the <UIGestureRecognizerDelegate> protocol

[self.myWebView addGestureRecognizer:tap];

Add the <UIGestureRecognizerDelegate> protocol in the header file, and add this method:

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

Solution 2:

If all you need is to handle gestures, while leaving the rest of the UIWebView functionality intact, you can subclass UIWebView and use this strategy:

in the init method of your UIWebView subclass, add a gesture recognizer, e.g.:

UISwipeGestureRecognizer  * swipeRight = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeGestureRightMethod)];
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self addGestureRecognizer:swipeRight];
swipeRight.delegate = self;

then, add this method to your class:

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

Add and handle your designated selector to the class, in this case "handleSwipeGestureRightMethod" and you are good to go...

Solution 3:

You could put an UIView over your UIWebView, and overide the touchesDidBegin etc, then send them to your webview. Ex:

User touches your UIView, which provokes a

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{  
    // Execute your code then send a touchesBegan to your webview like so:
[webView touchesBegan:touches withEvent:event];
return;
}

your UIView has to be over the webview.