UIWebView自适应内容高度

第一步:

let newContent = String(format:"<div id=\"webview_content_wrapper\">%@</div>",webViewContent)
self.newsDetailWebView!.loadHTMLString(newContent, baseURL: nil)


第二步:实现UIWebView代理:

func webViewDidFinishLoad(webView: UIWebView){
        
        //获取页面高度(像素)
        let clientheight_str = webView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight")
        let clientheight = Float(clientheight_str!)
        //设置到WebView上
        webView.frame = CGRectMake(0, 80, self.frame.size.width, CGFloat(clientheight!));
        //获取WebView最佳尺寸(点)
        let frame = webView.sizeThatFits(webView.frame.size)
        //获取内容实际高度(像素)
        let height_str = webView.stringByEvaluatingJavaScriptFromString("document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))")
        var height = Float(height_str!);
        //内容实际高度(像素)* 点和像素的比
        height = height! * Float(frame.height) / clientheight!;
        print("************\(height)")
}


猜你喜欢

转载自blog.csdn.net/chermon_love15/article/details/52671390