Search code examples
iosobjective-cuilabelnsattributedstring

Change first line color of UILabel


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.


Solution

  • 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];