美文网首页
WKWebView加载PC网页适应手机屏幕

WKWebView加载PC网页适应手机屏幕

作者: _沒看懂 | 来源:发表于2019-01-14 14:17 被阅读0次

    这里主要讲的是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">
    
    1. 初始化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;
    }
    
    1. 将配置设置给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;
    }
    

    相关文章

      网友评论

          本文标题:WKWebView加载PC网页适应手机屏幕

          本文链接:https://www.haomeiwen.com/subject/smwddqtx.html