【发布时间】:2013-02-13 15:04:46
【问题描述】:
我正在尝试使用 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;
我发现,如果我这样做,文本将不再呈现在标签中的多行上。它呈现为单行,在标签的框架中垂直居中。
这里有什么我遗漏的吗?
【问题讨论】:
-
你的标签足够高到第二行吗?
-
我无法在 6.1 上重现此内容。我注意到您的代码略有错误(setFont: 行中缺少 ],并且您在一个地方使用“label”而不是“contentLabel”)。你确定这是实际代码吗?
-
@Kevin Ballard:是的,标签够高了。
-
@KevinBallard:事实证明你是对的,我计算并分配给标签框架的所需高度不正确。感谢您让我走上正轨。
-
你可能应该写下你最后的评论作为答案并接受它,这样其他用户(比如我)会立即看到它。
标签: objective-c ios6 uilabel multiline nsattributedstring