webView.scrollView.contentSize.height並不是網頁最終加載出來的高度,這使得如果想實現上端爲網頁,下方爲原生評論列表效果存在高度計算誤差。本文就是給大家講述我的一個實現方法。也就是對webView.scrollView添加觀察者,從而檢測他的contentSize.height,一旦發生變化,及時更新。代碼如下
//添加觀察者
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 webView.scrollView.contentSize.height > webViewHeight || webView.scrollView.contentSize.height == 0 {
webViewHeight = webView.scrollView.contentSize.height
tableview.reloadData
}
}
}
如此就能實現實時監測網頁高度了,之所以要對比現在獲取到的網頁高度與上次的大小是爲了防止滑動時出現彈跳等bug。