2017-02-28 51 views
2

如何显示在下面的文字中UILabel内的UILabel显示HTML标记与指定字体

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; 
+0

这是因为斜体效果是里面的NSFontAttributed做到这一点。所以当你替换它时,你用全斜体替换整体字体。你必须迭代它,并找到相应的字体(如果它是斜体,把你的斜体定制一个,等等) – Larme

+0

可能重复[查找属性从用户键入的属性字符串](http://stackoverflow.com/questions/ 23153156 /找到的属性,从归于-字符串,也就是说,用户键入) – Larme

回答

0

如果你想使文本itallic的某些部分,那么你可以通过使用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];