尝试了JS代码获取、KVO监听两种方法来做,都不能满足要求
1、JS代码获取
//网页加载完成
//页面加载完后获取高度,设置脚,注意,控制器里不能重写代理方法,否则这里会不执行
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
// 不执行前段界面弹出列表的JS代码,关闭系统的长按保存图片
[self evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
// document.body.scrollHeight(不准) document.body.offsetHeight;(好)
[webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id Result, NSError * error) {
NSString *heightStr = [NSString stringWithFormat:@"%@",Result];
//必须加上一点
CGFloat height = heightStr.floatValue+15.00;
//网页加载完成
NSLog(@"新闻加载完成网页高度:%f",height);
}
这种方法只能在网页加载完成后调用一次,如果网页中有图片异步加载出来,则不会调用。
2、KVO监听ContentSize
[self. webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
一是会多次闪屏刷新,二是出现了高度无限增加的问题,也无法找到解决的办法,所以最后也没有采用
3、所以最终选择了H5返回高度的方法来实现
WKUserContentController* userContentController = WKUserContentController.new;
WKUserScript * cookieScript = [[WKUserScript alloc]
initWithSource: cookieValue
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:cookieScript];
[userContentController addScriptMessageHandler:self name:@"loadComplete"];
config.userContentController = userContentController;
// JS->OC JS调用的OC 获取点击回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"当前的name:%@, 当前的body:%@", message.name, message.body);
if ([message.name isEqualToString:@"loadComplete"]) {//试卷加载完成
NSDictionary *dic = message.body;
NSString *height = [dic objectForKey:@"height"];
self.webViewHeight = [height floatValue];
[self updateHeight];
}
}
H5来返回,执行的最为准确,且没有乱七八糟的问题
网友评论