wkWebView中插入原生view有很多方法, 其中webView设置scrollView.contentInset并添加原生的view到inset区域可以实现界面效果, 但是会造成wkWebView中h5代码中的点击失效,在此的方法是通过js代码注入空白view区域将原生view添加上去; 只需在webView加载完成的代理方法中插入空白view, 并在相应的区域将原生的view添加到webView.scrollView即可:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSString *js = [NSString stringWithFormat:@"\
var appendDiv = document.getElementById(\"AppAppendDIV\");\
if (appendDiv) {\
appendDiv.style.height = %@+\"px\";\
} else {\
var appendDiv = document.createElement(\"div\");\
appendDiv.setAttribute(\"id\",\"AppAppendDIV\");\
appendDiv.style.width=%@+\"px\";\
appendDiv.style.height=%@+\"px\";\
document.body.prepend(appendDiv);\
}\
", @(headHeight), @(self.webView.scrollView.contentSize.width), @(headHeight)];
[self.webView evaluateJavaScript:js completionHandler:nil];
}
// headHeight即为原生view的高度
// js代码最后一句document.body.prepend(appendDiv);\是将view加入到顶部
// 加入底部用:document.body.appendChild(appendDiv);\
//获取页面高度
[webView evaluateJavaScript:@"document.body.offsetHeight;"completionHandler:^(id _Nullable result,NSError *_Nullable error) {
//获取页面高度
NSLog(@"%@",result);
}];