美文网首页
iOS-WKWebView 加载HTML字符自适应文字和图片

iOS-WKWebView 加载HTML字符自适应文字和图片

作者: iOS祎 | 来源:发表于2022-05-23 14:24 被阅读0次

    加载HTML字符串内容时,字体自适应屏幕问题处理,在创建 WKWebView 时,注入相关的js:

    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    

    对于图片处理,图片高度自适应,在html富文本中加入

     NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                                   "<head> \n"
                                   "<style type=\"text/css\"> \n"
                                   "body {font-size:15px;}\n"
                                   "</style> \n"
                                   "</head> \n"
                                   "<body>"
                                   "<script type='text/javascript'>"
                                   "window.onload = function(){\n"
                                   "var $img = document.getElementsByTagName('img');\n"
                                   "for(var p in  $img){\n"
                                      " $img[p].style.width = '100%%';\n"
                                       "$img[p].style.height ='auto'\n"
                                   "}\n"
                                   "}"
                                   "</script>%@"
                                   "</body>"
                                   "</html>",htmlString];
        
        [self.webView loadHTMLString:htmls baseURL:nil];
    

    相关文章

      网友评论

          本文标题:iOS-WKWebView 加载HTML字符自适应文字和图片

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