最近項目里面遇見了 HTML 字符串,整理如下:
后臺返回字符串的樣式
在 iOS 中通常加載 HTML 字符串有兩種方式
- 通過 UILabel 加載富文本的方法加載 HTML 字符串
- 通過 WebView 加載 HTML 字符串
- (void)viewDidLoad {
[super viewDidLoad];
1.UILabel 加載 HTML 字符串
NSString * str1 = @"<div>Google(中文名:谷歌),是一家美國的跨國科技企業。</div><div>Google由當時在斯坦福大學攻讀理工博士的拉里·佩奇和謝爾蓋·布盧姆共同創建,因此兩人也被稱為“Google Guys”。</div><div>1998年9月4日,Google以私營公司的形式創立,設計并管理一個互聯網搜索引擎“Google搜索”。</div>";
NSString * str2 = @"<p><br></p>";
NSString * str3 = @"<p>qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq</p>";
//1.將字符串轉化為標準HTML字符串
str1 = [self htmlEntityDecode:str1];
//2.將HTML字符串轉換為attributeString
NSAttributedString * attributeStr = [self attributedStringWithHTMLString:str1];
//3.使用label加載html字符串
self.label.attributedText = attributeStr;
2.UIWebView 加載HTML字符串
UIWebView * webView = [[UIWebView alloc]initWithFrame:CGRectMake(20, 300, self.view.frame.size.width - 40, 400)];
[webView loadHTMLString:str1 baseURL:nil];
[self.view addSubview:webView];
self.webView = webView;
}
//將 < 等類似的字符轉化為HTML中的“<”等
- (NSString *)htmlEntityDecode:(NSString *)string
{
string = [string stringByReplacingOccurrencesOfString:@""" withString:@"\""];
string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"'"];
string = [string stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
string = [string stringByReplacingOccurrencesOfString:@">" withString:@">"];
string = [string stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; // Do this last so that, e.g. @"<" goes to @"<" not @"<"
return string;
}
//將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];
}
//去掉 HTML 字符串中的標簽
- (NSString *)filterHTML:(NSString *)html
{
NSScanner * scanner = [NSScanner scannerWithString:html];
NSString * text = nil;
while([scanner isAtEnd]==NO)
{
//找到標簽的起始位置
[scanner scanUpToString:@"<" intoString:nil];
//找到標簽的結束位置
[scanner scanUpToString:@">" intoString:&text];
//替換字符
html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
}
// NSString * regEx = @"<([^>]*)>";
// html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
return html;
}
作者:斷劍
鏈接:http://www.lxweimin.com/p/9605e7291fe3
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
注意
此處的字符串不是標準的標簽的HTML字符串,所以我們首先要調用- (NSString )htmlEntityDecode:(NSString )string 方法將字符串轉換成標準的HTML字符串,這樣才可以進行HTML字符串的加載
實例的第二個字符串中的內容為空,當用 Label 加載的時候只是兩行空白數據,此時可以調用- (NSString )filterHTML:(NSString )html 方法,去掉標簽,將HTML字符串轉換為常用的字符串樣式