2018-07-17使用iOSWebView加载html代码

参考文章
处理HTMLString的原理:

原理就是用一个for循环,拿到所有的图片,对每个图片都处理一次,让图片的宽为100%,就是按照屏幕宽度自适应;让图片的高atuo,自动适应。文字的字体大小,可以去改font-size:15px,这里我用的是15px。根据自己的具体需求去改吧。

NSString *content = [content stringByReplacingOccurrencesOfString:@"&quot" withString:@"'"];
    content = [content stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    content = [content stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    content = [content stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    
    NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                       "<head> \n"
                       "<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" /> \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>",content];
    
    
    [_webView loadHTMLString:htmls baseURL:nil];

问题是作者为什么要这么处理这些特殊字符呢?这五个字符其实是转义字符
"&amp;"就是'&' 只是在HTML中的&用&来表示

比如你要得到'&nbsp'的字符串,而不是空格,那就用&amp;nbsp

XML有5个转义符: &lt; &gt;&amp; &quot; &apos; 对应的是<>&"' 就是小于号,大于号,与符号,双引号,单引号
转义字符串(Escape Sequence)也称字符实体(Character Entity)。

在HTML中,定义转义字符串的原因有两个:

第一个原因是像“<”和“>”这类符号已经用来表示HTML标签,因此就不能直接当做文本中的符号来使用。为了在HTML文档中使用这些符号,就需要定义它的转义字符串。当解释程序遇到这类字符串时就把它解释为真实的字符。在输入转义字符串时,要严格遵守字母大小写的规则。

第二个原因是,有些字符在ASCII字符集中没有定义,因此需要使用转义字符串来表示。

- (NSString *)htmlEntityDecode:(NSString *)string
{
    string = [string stringByReplacingOccurrencesOfString:@"&quot;" withString:@"\""];
    string = [string stringByReplacingOccurrencesOfString:@"&apos;" withString:@"'"];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
 // Do this last so that, e.g. @"&amp;lt;" goes to @"&lt;" not @"<"

    return string;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容