简体   繁体   中英

iOS Swift WKWebView is not zooming

I am working on an iOS application that has a web view to load inside it. I am using WKWebView but it is not zooming.

I set minimum and maximum scale of webView's scrollView but still doesn't work.

@IBOutlet weak var webView: WKWebView!
webView.scrollView.minimumZoomScale = 0.1
webView.scrollView.maximumZoomScale = 1.0

How can I enable scaling of WKWebView ?

works on Xcode 11, swift 4 , iOS 12,13 . Implement WebView navigationDelegate

 let isAllowZoom: Bool = false

    override func viewDidLoad() {

            webView.scrollView.scrollEnabled = true               
            webView.scrollView.bounces = false                    
            webView.allowsBackForwardNavigationGestures = false   
            webView.contentMode = .ScaleToFill
            webView.navigationDelegate = self
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

            if(isAllowZoom){
              let javascript = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=10.0, user-scalable=yes');document.getElementsByTagName('head')[0].appendChild(meta);"
                webViewWB.evaluateJavaScript(javascript, completionHandler: nil)
            }
            else
            {

                 let javascript = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
                 webViewWB.evaluateJavaScript(javascript, completionHandler: nil)
            }

        }

then try this :

        webView.scrollView.scrollEnabled = true               
        webView.scrollView.bounces = false                    
        webView.allowsBackForwardNavigationGestures = false   
        webView.contentMode = .ScaleToFill
//  Set the WKWebView scroll view delegate
        webView.scrollView.delegate = self

Conform your vc to UIScrollViewDelegate and add it's delegate method viewForZoomingInScrollView to return nil as follows :

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

Hope it helps to get your page adopt native behavior

您必须通过添加以下内容将它的scalesPageToFit属性设置为true

webView.scalesPageToFit = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM