WKWebView高度精准自适应
2017-10-29 本文已影响983人
東玖零
原理:利用WKWebView 有提前注入一段js方法,在页面加载完成后调用此方法并获取返回值的能力。
前提:需要在html的body的最后加一个空标签,id为myid。
1.注入js代码(包含一个refreshView方法)
let js = "function refreshView () {" +
"var imgstyle=document.getElementsByTagName('img');" +
"for(var i=0;i<imgstyle.length;i++){" +
"imgstyle[i].style.width='\(k_screen_width)'+'px';" +
"imgstyle[i].style.height = 'auto';" +
"}" +
"return document.getElementById('myid').offsetTop;}"
2.拼接html并加载
let header = "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\"/><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\"><link rel=\"stylesheet\" type=\"text/css\" /><style type=\"text/css\"> </style></head>"
let div = "<div id='myid' style = 'width:100%;height:10px;background-color:green;display:block'></div>"
let html = "<html>" + header + "<body style='width:100%;background-color:red;padding:0px;margin:0px;display:block;'>" + body + div + "</body></html>"
self.wkWebView.loadHTMLString(html, baseURL: nil)
3.在加载完成后调用refreshView方法
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("refreshView()") {[weak self] (obj, error) in
// DLog(items: "-------obj = \(String(describing:obj)),error = \(String(describing: error))")
if let hasSelf = self {
hasSelf.evaluateJavaScript(obj: obj, error: error)
}
}
}
func evaluateJavaScript(obj:Any?, error:Error?) {
if let height = obj as? CGFloat {
// DLog(items: "height----\(height)")
if height != self.height {
self.frame = CGRect(x: 0, y: 0, width: k_screen_width, height: height)
self.wkWebView.frame = self.bounds
if let block = self.refresh {
block()
}
}
}
}
![](https://img.haomeiwen.com/i8733050/1518f30d8f3fd324.png)
![](https://img.haomeiwen.com/i8733050/8edb29e4bdccda96.png)
![](https://img.haomeiwen.com/i8733050/81be6e91de754906.png)