Different font size in the same label?

hugocarlmartin picture hugocarlmartin · Jan 17, 2013 · Viewed 8.2k times · Source

Is it possible to have different fontsize or weight in the same UILabel? I can do it in the storyboard as Attributed label, but I need to do it programmatically.

cell.lblOne.text = [NSString stringWithFormat:
                       @"FontSize15:: %@, FontSize20:: %@",monkey, goat];

Edit: I saw something about NSAttributedString but I can't get it to work.

Answer

foundry picture foundry · Jan 17, 2013

Take a look at my answer here:

UITextView Alternative

  • make an NSMutableAttributedString
  • give it some attributes (applied to ranges of characters)
  • set the label's attributedText property

.

 NSMutableAttributedString *attString = 
                              [[NSMutableAttributedString alloc]
                                        initWithString: @"monkey goat"];

[attString addAttribute: NSForegroundColorAttributeName
                  value: [UIColor redColor]
                  range: NSMakeRange(0,6)];


[attString addAttribute: NSFontAttributeName
                  value:  [UIFont fontWithName:@"Helvetica" size:15]
                  range: NSMakeRange(0,6)];

[attString addAttribute: NSFontAttributeName
                  value:  [UIFont fontWithName:@"Didot" size:24]
                  range: NSMakeRange(7,4)];

self.label.attributedText  = attString;