需求来源
从后台返回的数据是一个数组,每个数组元素是html字符串,可以显示在一个UIWebView中。
在显示这个html字符串的详情页面的上一级是一个列表,展示标题和内容简介。但是,后台返回的数据中并没有简介字段。
万能的交互和技术一商量,接口不改,让iOS和Android客户端从“html字符串”中抽出具体的内容,当成简介。列表就显示3行,多余的用...来表示。霸道而虚弱的后台,就算吐槽也没用。
方案一:NSAttributedString
项目最低支持iOS7,所以NSAttributedString可以使用,其中有一个option叫做NSHTMLTextDocumentType,就是专门用来从“html字符串”抽取纯文本的。iOS UILabel显示HTML文本
这种API比较难用,所以这里要记一下,希望苹果以后能提供好用一点的API
NSString *htmlString = @"
Some html string \n This is some text! ";NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel *myLabel = [[UILabel alloc] initWithFrame:self.view.bounds];