ios 附加带有换行符的 NSAttributedString 返回格式错误的属性字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22681008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending NSAttributedString with line break returns attributed string with wrong format
提问by user3404693
I'm using NSMutableAttributedString
and NSAttributedString
to display a label text in two different font sizes. My approach is:
我正在使用NSMutableAttributedString
和NSAttributedString
以两种不同的字体大小显示标签文本。我的做法是:
NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"days" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];
Which returns me an Attributed string with "2" in font size 12 and "days" in font size 8.
这会返回一个属性字符串,字体大小为 12,字体大小为“2”,字体大小为“天”。
However, the other scenario is to add a line break after 2. I use the following code:
但是,另一种情况是在 2 后添加换行符。我使用以下代码:
NSMutableAttributedString *muAtrStr = [[NSMutableAttributedString alloc]initWithString:@"2"];
NSAttributedString *atrStr = [[NSAttributedString alloc]initWithString:@"\ndays" attributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Bold" size:8]}];
[muAtrStr appendAttributedString:atrStr];
This time attributed string applies the attribute on the full text. I get an attributed string with "2\ndays" in font size 8.
这次属性字符串将属性应用于全文。我得到一个字体大小为“2\ndays”的属性字符串。
回答by Hussain Shabbir
Try this below code, it works fine:-
试试下面的代码,它工作正常:-
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];
Note:- Also put numberOfLines to 0 for allowing any number of lines
注意:- 也将 numberOfLines 设置为 0 以允许任意数量的行
回答by primulaveris
This works in Swift:
这适用于斯威夫特:
let attributedText = NSAttributedString(string: "Happy \nDays")
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedText = attributedText