Appending NSAttributedString with line break returns attributed string with wrong format

user3404693 picture user3404693 · Mar 27, 2014 · Viewed 44k times · Source

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];

Which returns me an Attributed string with "2" in font size 12 and "days" in font size 8.

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];

This time attributed string applies the attribute on the full text. I get an attributed string with "2\ndays" in font size 8.

Answer

Hussain Shabbir picture Hussain Shabbir · Mar 27, 2014

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