extension BusShopMallDetailsViewController{
func loadWebData() {
wkWebView.isUserInteractionEnabled = false
wkWebView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new,context:nil)
guard (productDetailsStr ?? "") != "" else {
return
}
let str = "<html> \n"
+ "<head> \n"
+ "<style type=\"text/css\"> \n"
+ "body {font-size:15px;}\n"
+ "</style> \n"
+ "</head> \n"
+ "<body>"
+ "<script type='text/javascript'>"
+ "window.onload = function(){\n"
+ "var $img = document.getElementsByTagName('img');\n"
+ "for(var p in $img){\n"
+ " $img[p].style.width = '100%';\n"
+ "$img[p].style.height ='auto'\n"
+ "}\n"
+ "}"
+ "</script><div style=\"font-size:36px\">\(productDetailsStr)</div>"
+ "</body>"
+ "</html>"
wkWebView.loadHTMLString(str, baseURL: nil)
wkWebView.sizeToFit()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "contentSize" {
if self.wkWebView.estimatedProgress == 1.0 && self.wkWebView.isLoading == false {//判断WebView加载完成
wkWebView.evaluateJavaScript("document.readyState") { [weak self] (readyState, readyStateError) in
guard let self = self else {return}
if let readyState = readyState as? String {
if readyState == "complete"{//加载完成了
self.wkWebView.evaluateJavaScript("document.body.scrollWidth",completionHandler: { [weak self](data, error ) in
guard let self = self else {return}
if let data = data as? CGFloat, data > 0 {
//计算缩放比
let ratio = self.wkWebView.frame.width / data
//offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度
self.wkWebView.evaluateJavaScript("document.body.offsetHeight",completionHandler: { [weak self](data, error ) in
guard let self = self else {return}
var height:CGFloat = data as? CGFloat ?? 0.0
height = height * ratio
print("#####高度:%@",height)
if self.webH != height {
self.webH = height
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .none)
}
})
}
})
}
}
}
}
}
}
}
网友评论