在指定字体的UILabel中显示HTML标签

3
如何在 UILabel 中显示以下文本:
While <em>La La Land </em>is a film emphasising the problems 

我尝试使用以下代码,但当与特定字体一起使用时,它无法显示在<em>标签(斜体呈现)内的文本的正确格式。

NSMutableAttributedString *attrHTMLText = [[NSAttributedString alloc] initWithData:[yourHTMTextHere dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil];
[attrHTMLText addAttribute:NSFontAttributeName value:yourLabel.font range:NSMakeRange(0, attrHTMLText.length)];
[attrHTMLText addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, attrHTMLText.length)];
Label.attributedText = attrHTMLText;

这是因为斜体效果在NSFontAttributed内部。因此,当您替换它时,您将用非斜体字体替换整个字体。您必须迭代它,并找到相应的字体(如果它是斜体,则放置您的自定义斜体字体等)。 - Larme
可能是查找用户输入的属性字符串中的属性的重复问题。 - Larme
1个回答

0

如果您想使文本的某些部分变为斜体,则可以使用NSMutableAttributedString来实现。

NSMutableAttributedString *strText = [[NSMutableAttributedString alloc] initWithString:@"While La La Land is a film emphasising the problems"];
[strText addAttribute:NSFontAttributeName
              value:[UIFont fontWithName:@"Helvetica-Italic" size:22]
              range:NSMakeRange(7, 16)];
[label setAttributedText: strText];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接