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;
最佳答案
将 NSAttributedString
与 NSHTMLTextDocumentType
之类的选项一起用作 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/