WKWebView加载url, 自适应宽高
- (WKWebView *)webView {
if (!_webView) {
_webView = [[WKWebView alloc] init];
//以下代码适配大小
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];
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:wkWebConfig];
[self.view addSubview:_webView];
_webView.navigationDelegate = self;
}
return _webView;
}
WKWebView加载htmlString、富文本, 自适应宽高(图片、视频播放器、文字)
//加载时拼接上header头
//如果要让图片宽度固定
//"<head><style>img{width:%f !important;height:auto}</style></head>
NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'><style>img{max-width:100%;}</style><style>video{max-width: 100%; width:auto; height:auto;}</style></header>";
[self.webView loadHTMLString:[headerString stringByAppendingString:_load_String ? _load_String : @""] baseURL:nil];
//加载完之后调整字体大小
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSString *fontLimitStr = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'",100];
[webView evaluateJavaScript:fontLimitStr completionHandler:nil];
}