簡體   English   中英

如何將WKWebview的容器內容高度調整為Webview內容?

[英]How to adjust WKWebview's container content height to the webview content?

我正在嘗試獲取WKWebview內容的正確高度和寬度,以將webview容器高度設置為webview內容。 我已經嘗試了很多關於堆棧溢出的解決方案。

使用此代碼,容器具有正確的高度,但是Web視圖的寬度太大(好像Web視圖已縮放)

override func viewDidLoad() {

    let webConfiguration = WKWebViewConfiguration()
    let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.viewForWebview.frame.size.height))
    self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
    webView.translatesAutoresizingMaskIntoConstraints = false
    self.viewForWebview.addSubview(webView)

    NSLayoutConstraint.activate([
         self.webView.topAnchor.constraint(equalTo: self.viewForWebview.topAnchor),
        self.webView.bottomAnchor.constraint(equalTo: self.viewForWebview.bottomAnchor),
        self.webView.leadingAnchor.constraint(equalTo: self.viewForWebview.leadingAnchor),
        self.webView.trailingAnchor.constraint(equalTo: self.viewForWebview.trailingAnchor)
        ])

    webView.uiDelegate = self
     webView.navigationDelegate = self
     webView.scrollView.isScrollEnabled = false

    let bodyHtml = "<html><head><meta name=\"viewport\" content=\"initial-scale=1.0\" />" + htmlString + "</body></html>";  
    webView.loadHTMLString(bodyHtml, baseURL: Bundle.main.resourceURL)
}

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

    self.heightWebviewConstraint.constant = self.webView.scrollView.contentSize.height
    self.view.setNeedsLayout()
    self.view.setNeedsUpdateConstraints()
}

我沒有嘗試添加<head>標記,而是嘗試使用了evaluateJavaScript ,但是在這種情況下,高度的容器太大,而Webview的寬度太大。

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

    self.webView.evaluateJavaScript("document.readyState", completionHandler: { (complete, error) in
        if complete != nil {
                self.webView.evaluateJavaScript("document.body.offsetHeight", completionHandler: { (height, error) in

                self.heightWebviewConstraint.constant = height as! CGFloat
                self.view.setNeedsLayout()
                self.view.setNeedsUpdateConstraints()
            })
        }

    })
}

我也嘗試添加特定CSS樣式(無viewport並沒有evaluateJavaScript ),在這種情況下的WebView寬度是好的,但高度的容器太小(我的WebView在頂部和底部裁剪)。

let bodyHtml = "<html><head> <style>  img {  width:auto; height:auto;  max-width:100%; </style></head><body>" + htmlString + "</body></html>"

我迷失了所有這些解決方案。

我認為您實際上已經很接近解決方案了。 我遇到了類似的問題,並設法通過評估javascript解決了它。 我們的實現略有不同,因為我們使用帶有嵌套WkWebViews作為安排子視圖的stackview。 但是我可以共享我們的代碼(刪除了stackview部分),您可以自己嘗試一下。

    func addAndLoadWebView(with url: URL) {
         let wkWebView = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
         wkWebView.translatesAutoresizingMaskIntoConstraints = false
         wkWebView.navigationDelegate = self
         wkWebView.scrollView.isScrollEnabled = false
         wkWebView.scrollView.bounces = false
         wkWebView.scrollView.bouncesZoom = false
         wkWebView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
         self.view.addSubview(wkWebView)
         wkWebView.load(URLRequest(url: url))
    }

    @available(iOS 12.0, *)
    func asyncGetHTMLHeight(_ webview: WKWebView, completion: @escaping (CGFloat) -> Void) {
        webview.evaluateJavaScript("document.body.offsetHeight") { (result, _) in
            guard let result = result as? CGFloat else {
                completion(0.0)
                return
            }
            completion(result)
        }
    } 

    @available(iOS 12.0, *)
    func compatibleMeasureImageContent(with webview: WKWebView) {
    webview.evaluateJavaScript("document.body.firstChild.offsetHeight") { (result, _) in
        guard let result = result as? CGFloat else {
            return
        }
        var height = result
        webview.evaluateJavaScript("document.body.firstChild.width") { (result, _) in
            guard let width = result as? CGFloat else {
                return
            }
            // do something with width and height here
            // in our case images come 1 by one since our html is delivered in parts. You might have to check each image tag for its height for this calculation to work.
            }
        }
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         self.asyncGetHTMLHeight(webView, completion: { newHeight in
             webView.frame.size.height = newHeight
             webView.removeConstraints(webView.constraints)
             webView.heightAnchor.constraint(equalToConstant: newHeight).isActive = true          
          })
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM