iOS 获取wkwebview 加载完毕的高度
要获取WKWebView加载完毕后的高度,可以使用WKWebView的scrollView的contentSize属性来获取。在WKWebView加载完成后,可以通过KVO观察contentSize的变化来获取最终的高度。
首先,将WKWebView的scrollView的contentSize属性添加为观察对象:
webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: [.new], context: nil)
然后,实现观察回调方法,当contentSize变化时,获取最终的高度:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "contentSize" {
if let webView = object as? UIScrollView {
let height = webView.contentSize.height
print("WebView加载完毕的高度为:\(height)")
}
}
}
最后,在适当的时机(例如WKWebView的didFinishNavigation回调方法中),移除观察者:
webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
这样就可以获取到WKWebView加载完毕后的高度了。
原文地址: https://www.cveoy.top/t/topic/i8GV 著作权归作者所有。请勿转载和采集!