Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending NSAttributedString with line break returns attributed string with wrong format

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.

like image 748
user3404693 Avatar asked Mar 27 '14 07:03

user3404693


2 Answers

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

like image 53
Hussain Shabbir Avatar answered Oct 18 '22 05:10

Hussain Shabbir


This works in Swift:

let attributedText = NSAttributedString(string: "Happy \nDays")
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedText = attributedText
like image 29
primulaveris Avatar answered Oct 18 '22 05:10

primulaveris