html代码
图1
样式一:"
测试内容信息无错
"
样式二:
padding: 0px 4px 0px 0px; text-align: left; margin: 0px 0px 10px;\\">你好
了的好莱坞去任何
图2
一、情景1:加载到UILabel上面(转换成富文本即可)
//1.将字符串转化为标准HTML字符串
NSString *str1 = [self htmlEntityDecode:htmlString];
//2.将HTML字符串转换为attributeString
NSAttributedString * attributeStr = [self attributedStringWithHTMLString:str1];
//3.使用label加载html字符串并将label添加到view上
self.label.attributedText = attributeStr;
[self.label setFrame:CGRectMake(100,100,200,300)];
[self.view addSubview:self.label];
//------html 转换成字符串
//将 < 等类似的字符转化为HTML中的“
- (NSString *)htmlEntityDecode:(NSString *)string
{
string &#61; [string stringByReplacingOccurrencesOfString:&#64;""" withString:&#64;"\\""];
string &#61; [string stringByReplacingOccurrencesOfString:&#64;"\&#39;" withString:&#64;"\&#39;"];
string &#61; [string stringByReplacingOccurrencesOfString:&#64;"
string &#61; [string stringByReplacingOccurrencesOfString:&#64;">" withString:&#64;">"];
string &#61; [string stringByReplacingOccurrencesOfString:&#64;"&" withString:&#64;"&"]; // Do this last so that, e.g. &#64;"
return string;
}
//------ 将html转换成富文本
//将HTML字符串转化为NSAttributedString富文本字符串
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
NSDictionary *options &#61; &#64;{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute :&#64;(NSUTF8StringEncoding) };
NSData *data &#61; [htmlString dataUsingEncoding:NSUTF8StringEncoding];
return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
//图2 中的样式2 可以会出现显示空白&#xff0c;可以通过去除html标签来处理
//去掉 HTML 字符串中的标签
- (NSString *)filterHTML:(NSString *)html
{ NSScanner * scanner &#61; [NSScanner scannerWithString:html];
NSString * text &#61; nil;
while([scanner isAtEnd]&#61;&#61;NO)
{
//找到标签的起始位置
[scanner scanUpToString:&#64;"
//找到标签的结束位置
[scanner scanUpToString:&#64;">" intoString:&text];
//替换字符
html &#61; [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:&#64;"%&#64;>",text] withString:&#64;""];
}
return html;
}
二、情景2&#xff1a;加载到UIWebView上面(替换html中部分的字符)
//1.将字符串转化为标准HTML字符串&#xff0c;(此处的字符串不是标准的标签的HTML字符串,将字符串转换成标准的HTML字符串&#xff0c;这样才可以进行HTML字符串的加载)
NSString *str1 &#61; [self htmlEntityDecode:htmlString];//调用情景1的方法
//2.UIWebView 加载HTML字符串
UIWebView * webView &#61; [[UIWebView alloc] initWithFrame:CGRectMake(20, 150, self.view.frame.size.width-20, 400)];
[webView loadHTMLString:str1 baseURL:nil];
[self.view addSubview:webView];
三、缓存html用RNCachingURLProtocol库。