Search code examples
iosobjective-ciphoneuilabelnsmutableattributedstring

How to set different color for Alphabets in uilabel


I want to set gray color for alphabets in uilabel. how to set range value for that in NSMutableAttributedString.

Example :

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"1.2 Sun - 3.4 Mon"];
[attrString beginEditing];
[attrString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range: ]; // how to set range here for alphabets
[attrString endEditing];

Solution

  • Try this.

    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"1.2 Sun - 3.4 Mon"];
    
    if([[attrString string] rangeOfString:@"Sun"].location != NSNotFound)
    {
         NSRange range2 = [[attrString string] rangeOfString:@"Sun"];
    
        [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range2];
    }
    
    if([[attrString string] rangeOfString:@"Mon"].location != NSNotFound)
    {
        NSRange range2 = [[attrString string] rangeOfString:@"Mon"];
    
        [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor grayColor] range:range2];
    }
    

    Happy coding :)