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 = [string stringByReplacingOccurrencesOfString:@""" withString:@"\\""];
string = [string stringByReplacingOccurrencesOfString:@"\'" withString:@"\'"];
string = [string stringByReplacingOccurrencesOfString:@"
string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];
string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"
return string;
}
//------ 将html转换成富文本
//将HTML字符串转化为NSAttributedString富文本字符串
- (NSAttributedString *)attributedStringWithHTMLString:(NSString *)htmlString
{
NSDictionary *options = @{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
NSData *data = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
return [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
}
//图2 中的样式2 可以会出现显示空白,可以通过去除html标签来处理
//去掉 HTML 字符串中的标签
- (NSString *)filterHTML:(NSString *)html
{ NSScanner * scanner = [NSScanner scannerWithString:html];
NSString * text = nil;
while([scanner isAtEnd]==NO)
{
//找到标签的起始位置
[scanner scanUpToString:@"
//找到标签的结束位置
[scanner scanUpToString:@">" intoString:&text];
//替换字符
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
}
return html;
}
二、情景2:加载到UIWebView上面(替换html中部分的字符)
//1.将字符串转化为标准HTML字符串,(此处的字符串不是标准的标签的HTML字符串,将字符串转换成标准的HTML字符串,这样才可以进行HTML字符串的加载)
NSString *str1 = [self htmlEntityDecode:htmlString];//调用情景1的方法
//2.UIWebView 加载HTML字符串
UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(20, 150, self.view.frame.size.width-20, 400)];
[webView loadHTMLString:str1 baseURL:nil];
[self.view addSubview:webView];
三、缓存html用RNCachingURLProtocol库。