WKWebView自适应
自适应屏幕宽度
在创建WKWebview时,添加js:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name','viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
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;
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];
webView.backgroundColor = [UIColor clearColor];
webView.UIDelegate = self;
webView.navigationDelegate = self;
[self.view addSubview:webView];
self.webView = webView;图片宽度自适应
在WKWebview的代理方法
didFinishNavigation
中添加图片自适应js:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//图片宽度适配
NSString *js = @"function imgAutoFit() { \
var maxwidth = %f;\
var imgs = document.getElementsByTagName('img'); \
for (var i = 0; i < imgs.length; ++i) {\
var img = imgs[i]; \
if(img.width > maxwidth){ \
img.width = maxwidth; \
}\
} \
}";
js = [NSString stringWithFormat:js, webView.frame.size.width];
[webView evaluateJavaScript:js completionHandler:nil];
[webView evaluateJavaScript:@"imgAutoFit();"completionHandler:nil];
[webView evaluateJavaScript:@"document.body.offsetHeight;"
completionHandler:^(id _Nullable any, NSError * _Nullable error) {
}];
webView.scrollView.contentOffset = CGPointZero;
}