在WKWebView添加头视图
2016-11-14 本文已影响1132人
LJ的ios开发
介绍两种方法添加头视图:
第一种方法:(有错误,调整中)
在WKScrollView上添加视图,且设置WKContentView在的位置,代码如下:
UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200)];
topView.backgroundColor = [UIColor purpleColor];
for (UIView *wkScrollView in self.webView.subviews) {
if ([NSStringFromClass(wkScrollView.class) isEqualToString:@"WKScrollView"]) {
for (UIView *wkContentView in wkScrollView.subviews) {
if ([NSStringFromClass(wkContentView.class) isEqualToString:@"WKContentView"]) {
CGRect frame = wkContentView.frame;
frame.origin.y = topView.frame.size.height;
frame.size.height += 200;
wkContentView.frame = frame;
break;
}
}
[wkScrollView addSubview:topView];
break;
}
}
第二种方法:
在显示的HTML的body下第一个节点添加一个空白的div,在WKNavigationDelegate中使用注入js方法写入。代码如下:
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified 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.insertBefore(appendDiv,document.body.children[0]);\
}", @(200), @(self.webView.scrollView.contentSize.width), @(200)];
[webView evaluateJavaScript:js completionHandler:nil];
}
注意:1.不能直接在scrollView上添加视图,因为视图会盖住web的显示。
2.不能使用webView的scrollView.contentInset进行添加头部视图,因为web滚动此区域就没有点击事件。