WKWebview获取高度问题-底部空白
1.注入js代码
// 提取html文件中所有图片标签,修改宽度为屏幕宽度,高度自适应
let js = "function resetImages () {" +
"var imgstyle=document.getElementsByTagName('img');" +
"for(var i=0;i<imgstyle.length;i++){" +
"imgstyle[i].style.width='\(SCREEN_WIDTH)'+'px';" +
"imgstyle[i].style.height = 'auto';" + "}"
let sc = WKUserScript.init(source: js, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let user = WKUserContentController()
user.addUserScript(sc)
let config = WKWebViewConfiguration()
config.userContentController = user
2.直接替换(简单粗暴)
let result = "<img style='display: block; max-width: 100%;'"
var contentStr = "<img src=\"https://gdp.alicdn.com/imgextra/i4/693060164/TB2YMPeaBLzQeBjSZFjXXcscpXa_!!693060164.jpg\" />"
contentStr = contentStr.replacingOccurrences(of: "<img", with: result)
3.以上两种方法对我都不适用(不是图片问题)
由于webView内容未做适配,使用屏幕宽度作为宽度时,对应的高度应该按比例进行适配
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
weak var weakself = self
var webWidth: CGFloat = 0
var webHeight: CGFloat = 0
webView.evaluateJavaScript("document.body.scrollHeight;") { (result, error) in
let height = CGFloat(((result as AnyObject).doubleValue)!)
webHeight = height
if webWidth > 0 && webHeight > 0 {
let realHeight = SCREEN_WIDTH * webHeight / webWidth
webView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: realHeight)
}
}
webView.evaluateJavaScript("document.body.scrollWidth;") { (result, error) in
let width = CGFloat(((result as AnyObject).doubleValue)!)
webWidth = width
if webWidth > 0 && webHeight > 0 {
let realHeight = SCREEN_WIDTH * webHeight / webWidth
webView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: realHeight)
}
}
}