Ivan Cantarino
Ivan Cantarino

Reputation: 3246

Disable WKWebView zooming

I have a WKWebView which I want to disable zooming. For that I have implemented the UIScrollViewDelegate viewForZooming(_:) delegate function in which I return nil as the following:

func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return nil
}

Somehow the WKWebView still zooms when I pinch and I don't want this effect.

I have set the WKWebView isMultipleTouchEnabled to false but this still doesn't disable zooming.

The only this that disabled zooming was setting the isUserInteractionEnabled to false but with this I cannot interact with links inside the WKWebView which isn't the desired thing.

This is how I declare my object and how it's being setup

private lazy var webView: WKWebView = {
    // script to fit the content with the screen
    var scriptContent = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"

    let wkuscript = WKUserScript(source: scriptContent, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
    let wkucontroller = WKUserContentController()
    wkucontroller.addUserScript(wkuscript)

    let wkwebconfig = WKWebViewConfiguration()
    wkwebconfig.userContentController = wkucontroller
    wkwebconfig.preferences.setValue(true, forKey: "developerExtrasEnabled")

    let wv = WKWebView(frame: .zero, configuration: wkwebconfig)
    wv.frame.size.height = 1
    wv.isOpaque = false
    wv.backgroundColor = .clear
    wv.scrollView.backgroundColor = Theme.collectionViewBackgroundColor
    return wv
}()

fileprivate func setupWKWebView() {
    addSubview(webView)
    webView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddinfLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)

    webView.scrollView.delegate = self
    webView.navigationDelegate = self   
}

Any hint what may be causing this?

Upvotes: 1

Views: 6395

Answers (1)

Khushbu
Khushbu

Reputation: 2430

Please try this to disabled zooming for pinch gesture.

func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
     scrollView.pinchGestureRecognizer?.isEnabled = false
}

Upvotes: 10

Related Questions