1. 程式人生 > >WKWebView加載的網頁自適應大小

WKWebView加載的網頁自適應大小

create brush pen eat conf navi att ini 屏幕

一,前言

有時候在WKWebView加載頁面後會發現頁面的字會很小, 這是因為原網頁沒有做手機屏幕尺寸的適配, 那麽在後臺不做調整的情況下我們移動端怎樣來適配頁面呢?
以下代碼可以適配大小(原本不可以左右滑動的可能會需要左右滑動才能完整查看)

二,實現方式

- (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); var imgs = document.getElementsByTagName(‘img‘);for (var i in imgs){imgs[i].style.maxWidth=‘100%‘;imgs[i].style.height=‘auto‘;}"
        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加載的網頁自適應大小