Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable magnification gesture in WKWebView

I'm looking for a way to disable the "pinch to zoom" magnification gesture on the iOS implementation of WKWebView. There is a magnification BOOL property available for OS X but it doesn't seem to be available on iOS.

WKWebView.h

#if !TARGET_OS_IPHONE /* @abstract A Boolean value indicating whether magnify gestures will  change the web view's magnification.  @discussion It is possible to set the magnification property even if  allowsMagnification is set to NO.  The default value is NO.  */ @property (nonatomic) BOOL allowsMagnification; 

I've, also, tried look at the WKWebView's gesture recognizers but that seems to be turning up an empty array. I'm assuming the actual recognizers are bured deeper in the component's structure (fairly complex, by the looks of it) and would rather not go digging for them if at all possible.

I know of possible hacks that could potentially disable the gesture from firing (selectively passing gestures to the WebView, add child view to capture pinch gesture, etc) but I've always found those introduce lag into the event and want to keep the implementation as clean/hack free as possible.

like image 370
Kevin Avatar asked Aug 28 '14 16:08

Kevin


2 Answers

You can prevent your users from zooming by setting the delegate of your WKWebKit's UIScrollView and implementing viewForZooming(in:) as in the following:

class MyClass {     let webView = WKWebView()      init() {         super.init()         webView.scrollView.delegate = self     }      deinit() {         // Without this, it'll crash when your MyClass instance is deinit'd         webView.scrollView.delegate = nil     } }  extension MyClass: UIScrollViewDelegate {     func viewForZooming(in scrollView: UIScrollView) -> UIView? {         return nil     } } 
like image 84
Landschaft Avatar answered Sep 23 '22 14:09

Landschaft


I have tried setting minimumZoomScale and maximumZoomScale properties of UIScrollView to 1 or isMultipleTouchEnabled property of UIView to false or returning nil from invoking viewForZooming(in:) of UIScrollViewDelegate but none worked. In my case, after several trial and error, the following works in my case [Tested on iOS 10.3]:

class MyViewController: UIViewController {    var webView: WKWebView?     override viewDidLoad() {       super.viewDidLoad()        //...       self.webView.scrollView.delegate = self       //...    } }  extension MyViewController: UIScrollViewDelegate {     func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {       scrollView.pinchGestureRecognizer?.isEnabled = false    } } 
like image 20
yohannes Avatar answered Sep 19 '22 14:09

yohannes