1. WKWebView加载的网页自适应大小
由于原网页没有做手机端的适配,所以有时WKWebView在加载页面后会发现文字变小了。那么问题来了,手机端怎么做适配页面?
直接上代码如下:
- (WKWebView *)webView
{
if (!_webView) {
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript *uScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
WKUserContentController *uCon = [[WKUserContentController alloc] init];
[uCon addUserScript:uScript];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController= uCon;
CGRect frame = CGRectMake(0, 0, kScreen_Width, kScreen_Height - NAV_HEIGHT);
_webView= [[WKWebView alloc] initWithFrame:frame configuration:config];
_webView.backgroundColor = [UIColor whiteColor];
// _webView.navigationDelegate = self;
}
return _webView;
}
2.WKWebView 禁止捏合手势 (放大缩小)
1. 添加代理、遵守协议 <WKNavigationDelegate>
_webView.navigationDelegate = self;
2. 实现代理方法
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
NSString *injectionJSString = @"var script = document.createElement('meta');" "script.name = 'viewport';" "script.content=\"width=device-width, user-scalable=no\";" "document.getElementsByTagName('head')[0].appendChild(script);";
[_webView evaluateJavaScript:injectionJSString completionHandler:nil];
}