Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

This works in Swift:

let attributedText = NSAttributedString(string: "Happy \nDays")
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedText = attributedText
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top