当我们涉及到webView和纯代码结合的时候,例如一个资讯详情,其它位置想加上我们的纯代码控件,可以计算出webView的高度,然后放到scrollView上,然后在scrollView下边或者什么位置,加上自己的纯代码内容就行了.
下边是计算UIWebView的高度:
第一种方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
}
第二种方法:
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
CGSize size = [webView sizeThatFits:CGSizeZero];
frame.size = size;
webView.frame = frame;
}
第三种方法:
- (void)viewDidLoad {
[super viewDidLoad];
webview.delegate = self;
[webview loadHTMLString:@"<div id='foo' style='background: red'>fdasfda</div>" baseURL:nil];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *output = [webview stringByEvaluatingJavaScriptFromString:@"document.getElementByIdx_x_x_x("foo").offsetHeight;"];
NSLog(@"height: %@", output);
}
下边是计算WKWebView的高度:
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecifiedWKNavigation *)navigation
{
[_webViewevaluateJavaScript:@"document.body.offsetHeight"completionHandler:^(id_Nullable result,NSError * _Nullable error) {
//获取页面高度,并重置webview的frame
_webViewHeight = [resultdoubleValue];
CGRect frame =webView.frame;
frame.size.height =_webViewHeight;
webView.frame = frame;
}];
}