使用换行符附加NSAttributedString会返回格式错误的属性字符串

时间:2014-03-27 07:35:53

标签: ios objective-c nsattributedstring

我正在使用NSMutableAttributedStringNSAttributedString来显示两种不同字体大小的标签文字。我的方法是:

NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"days" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];

它返回一个归因字符串,字体大小为12,字符大小为“2”,字体大小为8,为“days”。

但是,另一种情况是在2之后添加换行符。我使用以下代码:

NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"\ndays" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];

此时属性字符串在全文中应用属性。我得到一个字体大小为8的“2 \ ndays”的属性字符串。

2 个答案:

答案 0 :(得分:39)

尝试以下代码,它可以正常工作: -

NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"\ndays" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];
self.lbl.numberOfLines = 0;
[self.lbl setAttributedText:muAtrStr];

注意: - 也允许numberOfLines为0以允许任意数量的行

答案 1 :(得分:8)

这适用于Swift:

let attributedText = NSAttributedString(string: "Happy \nDays")
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedText = attributedText