<b>标记在UILabel属性字符串中不起作用

时间:2016-04-04 07:27:16

标签: ios objective-c uilabel

我将html字符串显示为属性文本,如果UILabel但很少有标签在UILabel中不起作用

lineLabel.numberOfLines=0;
 NSString* html = self.offerArray[0][@"description"];
NSString * htmlString = [NSString stringWithFormat: @"%@%@</body></html>",kHTMLHeadOffer,html];
htmlString = [htmlString stringByReplacingPercentEscapesUsingEncoding:NSUnicodeStringEncoding];
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UIFont *font = [UIFont fontWithName:kFontName size:kOrderFont]; [attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attrStr length])];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init] ;
[paragraphStyle setAlignment:NSTextAlignmentCenter];
[attrStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [attrStr length])];
lineLabel.attributedText = attrStr;

3 个答案:

答案 0 :(得分:1)

请尝试使用此代码一次。

NSString *htmlstr = @"<p>This text is normal.</p> <p><b>This text is bold</b>.
</p> <p><big>Bigger text</big></p> <font size=3 color=red>This is some text!</font>
<font size=2 color=blue>This is some text!</font> <font face=verdana color=green>This is 
some text!</font>"; 

NSAttributedString *strAttributed = [[NSAttributedString alloc]
initWithData: [htmlstr dataUsingEncoding:NSUTF8StringEncoding] options: 
@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes: nil
error: nil];

[_lblHtmlText setAttributedText:strAttributed];

这是输出屏幕。

enter image description here

答案 1 :(得分:0)

删除Font属性对我有用:)

我已从我的代码

中删除了以下行
 UIFont *font = [UIFont fontWithName:kFontName size:kOrderFont];
[attrStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, [attrStr length])];

答案 2 :(得分:0)

使用自定义字体将HTML转换为NSAttributedString时的重要观察

要使用哪种字体格式?

使用 .otf 字体作为自定义字体文件, .ttf 不正确支持HTML到NSAttributedString。

在项目中添加.ot​​f字体时要记住的重要事项 在添加Info.plist文件时,您需要提供全名(包括.otf扩展名),如下图所示

enter image description here

奖励

使用以下函数将我的HTML文本转换为NSAttributedString

let data = [
    {id:1, attribute:"A"}
  , {id:2, attribute:"b"}
  , {id:3, attribute:"C"}
  , {id:4, attribute:"A"}
  , {id:5, attribute:"e"}
  , {id:6, attribute:"C"}
  , {id:7, attribute:"g"}
  , {id:8, attribute:"h"}
  , {id:9, attribute:"A"}];

let result = Object.values(data.reduce((o, obj) => {
  o[obj.attribute] = (o[obj.attribute] || []).concat(obj);
  return o; 
}, {})).filter(({length}) => length>1).map(x=> x.map(({id}) => id));

console.log(result)