语言:swift4.2
Xcode版本:10.1
demo地址:
https://github.com/colourfulStar/DynamicHeightSample
思路:
对webView的scrollView的contentSize添加监听。网页加载完成之后更新webView的frame
核心代码:
func createSubviews() {
wkWebview.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0)
wkWebview.scrollView.showsHorizontalScrollIndicator = false
wkWebview.scrollView.showsVerticalScrollIndicator = false
wkWebview.scrollView.isScrollEnabled = false
wkWebview.load(URLRequest.init(url: URL.init(string: "https://www.jianshu.com/p/492fafa6df48")!))
wkWebview.scrollView.addObserver(self, forKeyPath: "contentSize", options: NSKeyValueObservingOptions.new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let point = change![NSKeyValueChangeKey.init(rawValue: "new")]
if point is CGSize {
let height = (point as! CGSize).height
var frame = self.wkWebview.frame
frame.size.height = height
self.wkWebview.frame = frame
self.mainTableView.tableFooterView = self.wkWebview
}
}