27

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.

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
user3404693
  • 555
  • 1
  • 8
  • 19
  • Please guide me if there is a better approach to do the needful. – user3404693 Mar 27 '14 at 07:43
  • You can also use `- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range` method of attributed string to set attribute to different part of attributed string. And `setLineBreakMode` of label to `NSLineBreakByWordWrapping`. – Akhilrajtr Mar 27 '14 at 08:00
  • For those who was stuck like me, set yourLabel.numberOfLines = 0; in the code. – Borzh Oct 02 '17 at 21:41

2 Answers2

43

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

Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56
14

This works in Swift:

let attributedText = NSAttributedString(string: "Happy \nDays")
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedText = attributedText
primulaveris
  • 966
  • 14
  • 20