iOS webView自適應(yīng)內(nèi)容高度(完美版)

/////////////////////////////初始化,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);

}


轉(zhuǎn)載自推酷

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容