NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString: @"document.body.offsetHeight"];之所以造成高度不準(zhǔn)確是因?yàn)樘O(píng)果的retina屏幕一個(gè)像素是2*2點(diǎn);比如說(shuō)圖片200*200個(gè)像素,則會(huì)變成在蘋(píng)果這里400*400個(gè)點(diǎn)(200*200個(gè)像素需要400*400個(gè)點(diǎn))
/////////////////////////////初始化孤紧,self.view是父控件/////////////////////////////////
_webView = [[UIWebView alloc] initWithFrame: CGRectMake(0,0, self.view.frame.size.width,0)];
_webView.delegate= self;
_webView.scrollView.bounces = NO;
_webView.scrollView.showsHorizontalScrollIndicator = NO;
_webView.scrollView.scrollEnabled = NO;
[_webView sizeToFit];
///////////////////////////////設(shè)置內(nèi)容矫户,這里包裝一層div呻顽,用來(lái)獲取內(nèi)容實(shí)際高度(像素)仆潮,htmlcontent是html格式的字符串//////////////
NSString * htmlcontent = [NSString stringWithFormat:@"
%@
", htmlcontent];
[_webView loadHTMLString:htmlcontent baseURL:nil];
////////////////////////////////delegate的方法重載////////////////////////////////////////////
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//獲取頁(yè)面高度(像素)
NSString * clientheight_str = [webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"];
floatclientheight = [clientheight_str floatValue];
//設(shè)置到WebView上
webView.frame = CGRectMake(0,0, self.view.frame.size.width, clientheight);
//獲取WebView最佳尺寸(點(diǎn))
CGSize frame = [webView sizeThatFits:webView.frame.size];
//獲取內(nèi)容實(shí)際高度(像素)
NSString * 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'))"];
floatheight = [height_str floatValue];
//內(nèi)容實(shí)際高度(像素)* 點(diǎn)和像素的比
height = height * frame.height / clientheight;
//再次設(shè)置WebView高度(點(diǎn))
webView.frame = CGRectMake(0,0, self.view.frame.size.width, height);
}