UILabel with text of two different colors

Peter picture Peter · Jun 28, 2011 · Viewed 99.6k times · Source

I want to display a string like this in a UILabel:

There are 5 results.

Where the number 5 is red in color and the rest of the string is black.

How can I do this in code?

Answer

João Costa picture João Costa · Mar 1, 2013

The way to do it is to use NSAttributedString like this:

NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];
[label setAttributedText: text];

I created a UILabel extension to do it.