首先是关键JS代码:
NSString *jScript =
@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}"
;然后初始化并加入JS片段:
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
[wkUController addUserScript:wkUScript];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
wk_web = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 0) configuration:wkWebConfig];
wk_web.navigationDelegate = self;
[_mScroll_View addSubview:wk_web];
然后执行展示内容方法:
[wk_web loadHTMLString:info.data.content baseURL:nil];
或者
[wk_web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:info.data.content]]];
最后代理方法高度操作:
//页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
[webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
NSString *heightStr = [NSString stringWithFormat:@"%@",any];
//下面的wkWeb已经可以完美展示了,不过我的界面是自定义的
wk_web.frame = CGRectMake(0, _headerImage.frame.origin.y + ScreenW, ScreenW, heightStr.floatValue);
//所以,我的界面最底部是scrollView,其中包含:其他的视图 + wk_web,注意:100 + ScreenW 就是其他的视图,举个简单的例子而已。
_mScroll_ViewHHH.constant = 100 + ScreenW + heightStr.floatValue;
}];
}
效果图: