WKWebView 加载页面的自适应大小 与 禁止捏合手势

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];

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。