Change first line color of UILabel

462 views Asked by At

I'm trying to change a UILabels first line's color. It's not working for some reason. Here is my code:

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

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:[label.text rangeOfString:@"\n"];];
[label setAttributedText: text];

I don't see any changes in the first line.

1

There are 1 answers

0
Inder Kumar Rathore On BEST ANSWER

The problem is here

[text addAttribute:NSForegroundColorAttributeName 
         value:[UIColor redColor] 
         range:[label.text rangeOfString:@"\n"]];

It will color only \n

You need range from 0 to start of \n


Edit : You can try this code (it's not tested but should work)

NSRange rangeOfNewLine = [label.text rangeOfString:@"\n"];
NSRange newRange = NSMakeRange(0, rangeOfNewLine.location);

[text addAttribute:NSForegroundColorAttributeName
           value:[UIColor redColor]
           range:newRange];