html - 如何根据html标签在UILabel中显示html文本?

标签 html ios objective-c nsattributedstring

   NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[stringFromHtml dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil]
   self.textLabel.attributedText = attrString;
   self.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:14.0];

此代码忽略 <b> </b><i> </i>标签,但对另一个标签使用react (\t\r\n
)

已编辑:

此代码仅适用于我,然后我评论第二行 ( NSFontAttributeName ) - 在这种情况下,字体是默认的,标签如 <b>, <i>不会被忽略。 但是如果我想要我的字体样式 - 标签再次被忽略...... wtf? :)

    NSMutableAttributedString *attrHTMLText = [[[NSAttributedString alloc] initWithData:[eventText dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil] mutableCopy];
    [attrHTMLText addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Light" size:14.0] range:NSMakeRange(0, attrHTMLText.length)];
    [attrHTMLText addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(0, attrHTMLText.length)];
    self.textLabel.attributedText = attrHTMLText;

最佳答案

NSAttributedStringNSHTMLTextDocumentType 之类的选项一起用作 NSDocumentTypeDocumentAttribute

//create NSMutableAttributedString for adding attributes as per required
NSMutableAttributedString *attrHTMLText = [[[NSAttributedString alloc] initWithData:[yourHTMTextHere dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil] mutableCopy];
//set font here
[attrHTMLText addAttribute:NSFontAttributeName value:yourLabel.font range:NSMakeRange(0, attrHTMLText.length)];
//set color here
[attrHTMLText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, attrHTMLText.length)];

//Now set attribute text to your Label
yourLabel.attributedText = attrHTMLText;

关于html - 如何根据html标签在UILabel中显示html文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33994184/

相关文章:

javascript - 砖石留下了几个缝隙

objective-c - 实现 Facebook iOS SDK - 无 "fbDidLogin"回调

ios - SiriKit 的局限性?

objective-c - 如何符号化用户通过电子邮件发送给我的 Mac OS X 应用程序的崩溃报告?

javascript - 如何使用超链接打开特定的网络浏览器?

javascript - html 中的动态列表( Bootstrap 列表)

python - Objective-C 中常用的数组选项

iphone - 如何下载iphone的youtube视频-以编程方式使用Objective-C

javascript - 获取 getElementsByName 返回的对象的标签名称

ios - 为什么 tableview.visibleCells 为空?