I have read lots of articles about how to get height of the webView. Most of them use KVO to observe the contentSize. I also did that.
1) create wkWebView and forbid webView's 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) add observer
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) remove observer
deinit {
webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
}
When I run the app, sometimes I can get the correct height of the webView which was show right. Like below images
But sometimes ,the height of the webView over the correct height , it cause webView have part of empty space. We can see the below images, it get the wrong contentSize,
And when I tap the nextButton to load the new content, it also keep the previous height. That's not good. Just like if the contentSize's height over the new content's height. It will not change.
In order to compare wkWebView, so I have tried UIWebView, it was correct. So, I don't know how to solve that problem. Please give me some suggestions. Thanks




If the
contentSizeof the page you're rendering is less than theboundsof theWKWebView, thecontentSizewill be at least the same as thebounds, which results in a blank space.The only way you could get around this was to set the
boundsof yourWKWebViewto something less than the size of the content. Once the page renders you will know the size of theWKWebView.scrollView'scontentSizeand you can size it using your logic above.