这里主要讲的是html页面是pc上的网页,在手机上显示会文字过小,相当的不友好,加一个meta标签并添加相应的属性,就可以解决。
要添加的标签
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
- 初始化WKWebViewConfiguration配置js动态插入meta标签
- (WKWebViewConfiguration *)wkConfig {
if (!_wkConfig) {
_wkConfig = [[WKWebViewConfiguration alloc] init];
_wkConfig.allowsInlineMediaPlayback = YES;
if (@available(iOS 9.0, *)) {
_wkConfig.allowsPictureInPictureMediaPlayback = YES;
} else {
// Fallback on earlier versions
}
//自适应屏幕宽度js
NSString *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];
_wkConfig.userContentController = wkUController;
}
return _wkConfig;
}
- 将配置设置给WKWebView
- (WKWebView *)wkWebView {
if (!_wkWebView) {
_wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) configuration:self.wkConfig];
_wkWebView.navigationDelegate = self;
_wkWebView.UIDelegate = self;
// 这行代码可以是侧滑返回webView的上一级,而不是根控制器(*只针对侧滑有效)
[_wkWebView setAllowsBackForwardNavigationGestures:YES];
_wkWebView.scrollView.showsVerticalScrollIndicator = NO;
[self.view addSubview:_wkWebView];
}
return _wkWebView;
}
网友评论