簡體   English   中英

無法獲得 wkWebView 的正確高度?

[英]Couldn't get the correct height of the wkWebView?

我已經閱讀了很多關於如何獲取 webView 高度的文章。 他們大多使用 KVO 來觀察 contentSize。 我也這樣做了。

1)創建wkWebView並禁止webView的scrollView

 lazy var webView: WKWebView = WKWebView()

 webView.scrollView.bounces = false
 webView.scrollView.isScrollEnabled = false

 webView.snp.makeConstraints({ (make) in
        make.left.right.equalTo(view)
        make.top.equalTo(headerView.snp.bottom)
        make.height.equalTo(AppDefaults.screenH - 64 - 44)
        make.bottom.equalTo(containView)
    })

2)添加觀察者

webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "contentSize" {
        if let scroll = object as? UIScrollView {
            if scroll.contentSize.height > 0 {
                updateWebViewConstraints(scroll.contentSize.height)
            }
        }
    }
}

func updateWebViewConstraints(_ height: CGFloat) {
    webView.snp.remakeConstraints { make in
        make.left.right.equalTo(view)
        make.top.equalTo(headerView.snp.bottom)
        make.height.equalTo(height)
        make.bottom.equalTo(containView).offset(-44)
    }
}

3) 移除觀察者

deinit {
    webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
}

當我運行應用程序時,有時我可以獲得正確顯示的 webView 的正確高度。 喜歡下面的圖片

在此處輸入圖片說明

在此處輸入圖片說明

但有時,webView 的高度超過了正確的高度,會導致 webView 有一部分空白。 我們可以看到下面的圖片,它得到了錯誤的 contentSize,

在此處輸入圖片說明 在此處輸入圖片說明

當我點擊 nextButton 加載新內容時,它也會保持之前的高度。 那不好。 就像 contentSize 的高度超過新內容的高度一樣。 它不會改變。

為了對比wkWebView,所以嘗試了UIWebView,是正確的。 所以,我不知道如何解決這個問題。 請給我一些建議。 謝謝

如果您呈現的頁面的contentSize小於WKWebViewbounds ,則contentSize將至少與bounds相同,這會導致空白。

解決此問題的唯一方法是將WKWebViewbounds設置為小於內容大小的值。 頁面呈現后,您將知道WKWebView.scrollViewcontentSize大小,您可以使用上面的邏輯調整它的大小。

extension ViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.webViewHeightConstraint?.constant = 0
        self.view.layoutIfNeeded()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.webViewHeightConstraint?.constant = webView.scrollView.contentSize.height
        self.view.layoutIfNeeded()
    }
}

我遇到了同樣的問題。 基於runmad的解決方案,加載前將高度設置為零,然后設置正確的高度。

暫無
暫無

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

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