Swipe Gesture Recognition Inside UIWebView

MrHappyAsthma picture MrHappyAsthma · Aug 8, 2012 · Viewed 10.5k times · Source

I have read a bunch of questions on this but none of them seem to achieve what I am looking for... So lets say I have an arbitrary UIWebView inside of a UIViewController. The UIViewController has a SwipeGestureRecognizer that works fine. It even works within the UIWebView-- whenever there is no scrollbar. (Before I load a page or even if I load a page that can fit appropriately within the size of my UIWebView). However, if I load a webpage that requires horizontal scrolling left or right, then inside the UIWebView part of my view, I cannot get any swipe gestures to be recognized. Every click/drag/swipe just triggers the scroll action. Is there a way to differentiate between a "swipe" and just scrolling with your finger (not lifting it but rather dragging to scroll).

Answer

Johannes Fahrenkrug picture Johannes Fahrenkrug · Sep 16, 2013

Yes, you can tell the UIWebView's UIScrollView that its UIPanGestureRecognizer should only fire when your own UISwipeGestureRecognizer has failed.

This is how you do it:

UISwipeGestureRecognizer *rightSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
UISwipeGestureRecognizer *leftSwipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
rightSwipeGesture.direction = UISwipeGestureRecognizerDirectionRight;
leftSwipeGesture.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:rightSwipeGesture];
[self.view addGestureRecognizer:leftSwipeGesture];

[_webView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:rightSwipeGesture];
[_webView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:leftSwipeGesture];

That should do the trick for you.