【问题标题】:Couldn't get the correct height of the wkWebView?无法获得 wkWebView 的正确高度?
【发布时间】:2017-11-03 03:20:37
【问题描述】:

我已经阅读了很多关于如何获取 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,是正确的。所以,我不知道如何解决这个问题。请给我一些建议。谢谢

【问题讨论】:

    标签: ios swift webview uiscrollview contentsize


    【解决方案1】:

    如果您正在呈现的页面的contentSize 小于WKWebViewbounds,则contentSize 将至少与bounds 相同,这会导致空白.

    解决此问题的唯一方法是将boundsWKWebView 设置为小于内容大小的值。页面呈现后,您将知道WKWebView.scrollViewcontentSize 的大小,您可以使用上面的逻辑调整其大小。

    【讨论】:

    • 首先谢谢。如果我正在渲染的页面的 contentSize 小于 WKWebView 的 bounds,那么 contentSize 将至少与 bounds 相同。我知道。你说这是正确的方法。对我来说,第二个条件是 contentSize 的高度超过了正确的 contentSize。这意味着当 contentSize 的高度超过 screenHeight 时。它会导致那个问题。我之前也设置了 webView 约束。
    【解决方案2】:
    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的解决方案,加载前将高度设置为零,然后设置正确的高度即可。

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 2014-11-10
      • 2011-02-22
      • 2018-10-09
      • 1970-01-01
      相关资源
      最近更新 更多