首先是关键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;
}];
}
效果图:

本文介绍如何使用WKWebView及WKUserScript实现iOS应用内网页图片自适应,并通过JavaScript调整viewport和图片尺寸,确保内容在不同屏幕尺寸上的正确显示。
&spm=1001.2101.3001.5002&articleId=77944163&d=1&t=3&u=141753ff397247fb9ed18dba85b8f34a)
1046

被折叠的 条评论
为什么被折叠?



