WKWebView自适应屏幕宽高

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头
NSString *headerString = @"
"; [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]; }

你可能感兴趣的:(WKWebView自适应屏幕宽高)