问题描述
我正在使用 NSMutableAttributedString
和 NSAttributedString
来显示两种不同字体大小的标签文本。我的方法是:
I'm using NSMutableAttributedString
and NSAttributedString
to display a label text in two different font sizes. My approach is:
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且字体大小为days的归属字符串8。
Which returns me an Attributed string with "2" in font size 12 and "days" in font size 8.
但是,另一种情况是在2之后添加换行符。我使用以下代码:
However, the other scenario is to add a line break after 2. I use the following code:
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 \\\的字符串。
This time attributed string applies the attribute on the full text. I get an attributed string with "2\ndays" in font size 8.
推荐答案
试试下面的代码,它运行正常: -
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];
注意: - 也允许numberOfLines为0以允许任意数量的行
Note:- Also put numberOfLines to 0 for allowing any number of lines
这篇关于使用换行符附加NSAttributedString会返回格式错误的属性字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!