第一步:
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)")
}