当我们涉及到webView和自定义控件结合的时候,例如一个资讯详情,上半部分是webView,下面位置想加上我们的自定义控件,可可以计算出webView的高度,在刷新界面.
下边是计算UIWebView的高度:
-(void)webViewDidFinishLoad:(UIWebView *)webView{
// 计算UIWebView高度
CGRect frame =webView.frame;
frame.size.height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
webView.frame = frame;
}
-(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
{
// 计算WKWebView高度
[webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
CGRect frame =webView.frame;
frame.size.height =[result doubleValue];
webView.frame = frame;
}];
}