美文网首页
swift使用webView加载html

swift使用webView加载html

作者: pomelo_西 | 来源:发表于2019-03-22 12:24 被阅读0次
  1. 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
    }
  1. 加载html
bodyWebView.loadHTMLString(formatHtml(str: body), baseURL: nil)
  1. 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)
     }
}

相关文章

网友评论

      本文标题:swift使用webView加载html

      本文链接:https://www.haomeiwen.com/subject/uyulvqtx.html