美文网首页
WKWebView1 加载图文富文本

WKWebView1 加载图文富文本

作者: 孤雁_南飞 | 来源:发表于2021-05-18 18:53 被阅读0次

    wkwebview 加载带有图文的富文本,有很多显示不全的, 而且网上很多方法都是不能达到这种效果的
    有的是单单文字还好,加上图片之后,会出现各种问题


    WeChat8bfe7f80dcbf4eb9a2c8e126291df277.png

    例如这种:

    let path = """
                <p><img src="http://img.youluwx.com/qa/20210222/image/9369cb64-9119-4f46-a3bc-51c761698230.png"></p>
                <p>2021年<a href="http://www.niceloo.com/cjkj/" target="_blank" style="color: rgb(0, 0, 255);">初级会计师</a>5月15日开考,小编给考生准备了现阶段的学习规划,希望对考生有所帮助!</p><p>学前提示:初级会计师考试一年考试批次众多,考题覆盖面广,学习难度较大,而且对于没有会计基础的学员来说,学习起来更吃力,在学习中需要付出更多的时间和精力学习。学习会计实务要建立在理解的基础上清楚把握各业务的会计账务处理,切忌死记硬背。各章内容重要性程度不同,在学习中要有所侧重,但在基础阶段建议认真系统学一遍。鉴于此,为了提高大家的学习效率,我们提供以下复习计划,供广大考生参考。</p>
                <p><img src="http://img.youluwx.com/qa/20210222/image/13cc6318-1945-46ca-ae85-0792295d482f.png"><img src="http://img.youluwx.com/qa/20210222/image/ef33809a-5a65-4cd8-8ddf-af299429c47d.png"></p>
                """ 
    

    1.解决办法一
    swift

    lazy var webView: WKWebView = {
             
            let preference = WKPreferences()
            preference.javaScriptCanOpenWindowsAutomatically = true
             
            //图片 
            let imageString = "var objs = document.getElementsByTagName('img');for(var i=0;i++){var img = objs[i];img.style.maxWidth = '100%';img.style.height='auto';}"
            //文字 
            let textString = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
            let wkUscriptImage = WKUserScript(source: imageString, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
            let wkUscriptText = WKUserScript(source: textString, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
            
            let wkUController = WKUserContentController()
            wkUController.addUserScript(wkUscriptImage)
            wkUController.addUserScript(wkUscriptText)
            
            let wkWebConfig = WKWebViewConfiguration.init()
            wkWebConfig.userContentController = wkUController
            wkWebConfig.preferences = preference
            
            let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height), configuration: wkWebConfig)
            webView.uiDelegate = self
            webView.navigationDelegate = self
            webView.backgroundColor = .white
            
            webView.isMultipleTouchEnabled = true
            webView.isUserInteractionEnabled = true
            webView.contentMode = .scaleAspectFit
            
            return webView
        }()
    

    oc

    
    - (WKWebView *)webView {
        if (_webView == nil) {
            //通过WKUserScript注入JavaScript脚本和WKPreferences设置字体大小
             WKPreferences * preference = [[WKPreferences alloc] init];
             preference.javaScriptCanOpenWindowsAutomatically = YES;
    
             //图片自适应宽高
             NSString * jsImage = @"var objs = document.getElementsByTagName('img');for(var i=0;i++){var img = objs[i];img.style.maxWidth = '100%';img.style.height='auto';}";
             WKUserScript * wkUScriptImage = [[WKUserScript alloc] initWithSource:jsImage injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
             //文字修改大小
             NSString * jsText = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
             WKUserScript * wkUScriptText = [[WKUserScript alloc] initWithSource:jsText injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
             WKUserContentController * wkUController = [[WKUserContentController alloc] init];
             [wkUController addUserScript:wkUScriptImage];
             [wkUController addUserScript:wkUScriptText];
             //配置对象
             WKWebViewConfiguration * wkWebConfig = [[WKWebViewConfiguration alloc] init];
             wkWebConfig.userContentController = wkUController;
             wkWebConfig.preferences = preference;
    
            WKWebView * web = [[WKWebView alloc] initWithFrame:CGRectZero configuration:wkWebConfig];
            web.UIDelegate = self;
            web.navigationDelegate = self;
    //        web.scrollView.scrollEnabled = NO;
            web.backgroundColor = [UIColor whiteColor];
            
            web.multipleTouchEnabled = YES;
            web.userInteractionEnabled = YES;
            web.contentMode = UIViewContentModeScaleAspectFit;
             
            _webView = web;
        }
        return _webView;
    }
    

    然后使用 WKWebView 加载

     webView.loadHTMLString(path, baseURL: nil)
    

    这种的话,很多情况下可以加载成功,我之前就是一直这样处理的,但是这次就例外了,没办法,只能另想它法了
    2.解决方法二
    把之前的富文本转换一下,可解决图片宽度过宽等问题

    func stringToHTML(_ str: String) -> String { 
            let tempStr = "<head><style>img{width:\(UIScreen.main.bounds.size.width) !important;height:auto}</style></head>\(str)"
            return head + tempStr
        }
    

    然后加载

    webView.loadHTMLString(stringToHTML(path), baseURL: nil)
    

    完美解决,上边那个图片的处理可以取消了(我也是找了很久才找到解决方法的)


    WeChat1b8653256ab91269a23807bb1e1b870a.png
    1. 当富文本图片添加宽度时候,上面两种有时候加载不全图片,(备注:放到cell里面的wkwebview加载没问题,但是放到viewcontroller 里面的死活就是不行,希望大佬解惑)
    <p>这是文章内容</p>
    <p><img class="wscnph" src="http://122.51.171.40:9000/bucket/files/1480506069074710528.jpg" width="800" /></p>
    

    就是因为多了这一个 width="800" / 宽度始终不能自适应屏幕,去掉使用方法二就没问题,

    解决方案:

    swift

    let head = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>"
    
    let tempStr = "<head><style>img{width:\(UIScreen.main.bounds.size.width) !important;height:auto}</style></head>\(str)"
    
    let path = head + tempStr
    
    
    image.gif

    oc

    NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";
        NSString *adaptString = [NSString stringWithFormat:@"<head><style>img{max-width:100%% !important;height:auto !important}</style></head>%@", [NSString stringWithFormat:@"%@<br><br>", mallArticleModel.content]];
        NSString * path = [headerString stringByAppendingString:adaptString]; 
    
    image.gif

    下一篇:WKWebView 2 图文富文本, 点击图片

    相关文章

      网友评论

          本文标题:WKWebView1 加载图文富文本

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