Search code examples
iosobjective-cnsstringuilabelnsattributedstring

How to set the different color for numbers present in NSString dynamically


How to set the different color for numbers and words present in NSString dynamically.

I need this without using other classes. Is there any easy way to do it with NSAttributedString. I need this for UILabel.

Eg: 1 ball, 1 bat, 3 stumps, 4 Gloves,... n. etc*

I want the counts in one color and the item names in other color. Any help is appreciated.


Solution

  • You can use NSRegularExpression to find numbers in your text and after that just add attribute to the attribute string:

        NSString *testString = @"1 ball, 1 bat, 3 stumps, 4 Gloves";
        NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:testString];
    
        NSRange   searchedRange = NSMakeRange(0, [testString length]);
        NSString *pattern = @"\\d+";
        NSError  *error = nil;
    
        NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    
        NSArray* matches = [regex matchesInString:testString options:0 range: searchedRange];
        for (NSTextCheckingResult* match in matches)
        {
            NSString* matchText = [testString substringWithRange:[match range]];
            [attStr addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:[match range]];
            NSLog(@"Match: %@", matchText);
        }
        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
        lab.attributedText = attStr;
        [self.view addSubview:lab];