美文网首页
WKWebView加载HTML标签注意事项

WKWebView加载HTML标签注意事项

作者: 姚姚先生 | 来源:发表于2019-05-15 15:55 被阅读0次
    首先解决自适应屏幕宽度的问题
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        WKUserContentController *content = [[WKUserContentController alloc]init];
        // 自适应屏幕宽度js
        NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        // 添加自适应屏幕宽度js调用的方法
        [content addUserScript:wkUserScript];
        wkWebConfig.userContentController = content;
        
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth , 0) configuration:wkWebConfig];
        webView.scrollView.bounces = NO;
        webView.UIDelegate = self;
        webView.navigationDelegate = self;
        webView.scrollView.scrollEnabled = NO;
        self.webView = webView;
        [self.mainScrollView addSubview:webView];
    
    其次计算高度
    - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
    {
        //修改字体大小 300%
    //    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];
        
        //修改字体颜色  #9098b8
    //    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#0078f0'" completionHandler:nil];
        
        __block CGFloat webViewHeight;
        
        //获取内容实际高度(像素)@"document.getElementById(\"content\").offsetHeight;"
        [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
            // 此处js字符串采用scrollHeight而不是offsetHeight是因为后者并获取不到高度,看参考资料说是对于加载html字符串的情况下使用后者可以(@"document.getElementById(\"content\").offsetHeight;"),但如果是和我一样直接加载原站内容使用前者更合适
            //获取页面高度,并重置webview的frame
            webViewHeight = [result floatValue];
            webView.height = webViewHeight;
            self.mainScrollView.contentSize = CGSizeMake(KScreenWidth, webView.top + webViewHeight);
            NSLog(@"%f",webViewHeight);
            
            
        }];
    
    }
    
    
    如果加载HTML图片的时候失败,可能是info.plist文件没加网络权限
    Allow Arbitrary Loads in Web Content   
    Allow Arbitrary Loads
    

    相关文章

      网友评论

          本文标题:WKWebView加载HTML标签注意事项

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