- format好html字符串
func formatHtml(str: String) -> String {
// 为图片路径添加domain
let body = str.replacingOccurrences(of: "/sites", with: "https://cloudgym.sharecircle.cn/sites")
// 设置图片样式,给body加上id,以便获取
let htmlhead = "<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<meta charset=\"UTF-8\">" +
"<style type=\"text/css\">" +
"html{margin:0;padding:0;}" +
"body {" +
"margin: 0;" +
"padding: 0;" +
"}" +
"img{" +
"width: 100%;" +
"height: auto;" +
"display: block;" +
"margin-left: auto;" +
"margin-right: auto;" +
"}" +
"</style>" +
"</head>" +
"<body>" +
"<div id=\"webview_content_wrapper\">"
let htmlEnd = "</div></html>"
let content = htmlhead + body + htmlEnd
return content
}
- 加载html
bodyWebView.loadHTMLString(formatHtml(str: body), baseURL: nil)
- webViewDidFinishLoad()方法
webView加载完调用此方法,可以在此方法里获取当前webView的高度以及内容的给高度
extension DetailTableViewCell: UIWebViewDelegate {
func webViewDidFinishLoad(_ webView: UIWebView) {
// 根据content设置webView的高度
let contentHeightStr = bodyWebView.stringByEvaluatingJavaScript(from: "document.getElementById('webview_content_wrapper').clientHeight")
contentHeight = CGFloat((contentHeightStr! as NSString).floatValue)
}
}
网友评论