要显示一段文字
本来呢,WebView加载下面这段html文本就可以。
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style>
* { margin:0 !important; padding:0 !important; border:0 !important; }
html, body { width:100% !important; height:auto !important; min-height:0 !important; overflow:hidden !important; }
body { line-height:1.2 !important; display:inline-block !important; width:100% !important; }
img { max-width: 50vw; max-height: 50vw; object-fit: contain; display: block; margin: 0 auto; }
</style>
</head>
<body>
\(html) <!-- 这里是实际要显示的内容 -->
</body>
</html>
遇到的问题
Swift通过WebView加载html文本,WebView宽度固定,高度不固定。
(又涉及到UITableViewCell重用,不过这里不用考虑,我把问题简化掉)
需要动态获取WebView的高度,用于SnapKit调整height约束的高度,
就是回头在更新到高度后,heightConstraint.update(domHeight)就行。
- 那我先加代理
class xxx: UIView, WKNavigationDelegate {
...
webview.delegate = self
...
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.body.scrollHeight") { result, error in
guard let domHeight = result as? CGFloat, error == nil else { return }
self.heightConstraint.update(offset: domHeight)
}
}
...
}
- 但是
有时候,明显就一行字,字号常规,也就10几,能返回90,离谱。
尝试document.documentElement.scrollHeight或者document.body.scrollHeight都不行
解决方案
1. 改html
<body>
\(html) <!-- 这里是实际要显示的内容 -->
</body>
改为:
<body>
<div id="AIChatMessageCellWebViewContentDiv">
\(html) <!-- 这里是实际要显示的内容 -->
</div>
</body>
就是明确地给我的内容加个容器,回头只获取这个容器的高度,不管html,不管body。因为不知道为什么他们的高度就不对了。烦死。
2. 改javascript
代理方法里面的
"document.body.scrollHeight"
改为:
"document.getElementById(\"AIChatMessageCellWebViewContentDiv\").scrollHeight"
也是明确地只获取我那个容器的高度。