我正在尝试使用NSMutableAttributedString创建多行UILabel . 当我将属性分配给完整的字符串时,这样可以正常工作:
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(0, [string length])];
contentLabel.attributedText = string;
但我需要的是为NSAttributedString的不同子范围应用许多属性(以加粗某些单词) .
UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,200,100)];
[contentLabel setLineBreakMode:NSLineBreakByWordWrapping];
[contentLabel setNumberOfLines:0];
[contentLabel setFont:[UIFont systemFontOfSize:13];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello I am a long sentence that should break over multiple lines"];
[string addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13] range:NSMakeRange(3, 5)];
contentLabel.attributedText = string;
我发现的是,如果我这样做,文本将不再在标签中的多行上呈现 . 它呈现为单行,在标签的框架中垂直居中 .
这里有什么我想念的吗?
2 回答
正如问题评论中所讨论的那样,问题中提供的代码实际上可以正常工作,并且确实按照预期呈现了属性字符串 . (问题在我的代码中的其他地方)
我经常使用UITextView并为其分配一个以类似方式归属的文本: