iosobjective-cnsmutableattributedstring

Highlight or Underline Specific Word in a String


I would like to highlight or underline a specific set of words in a NSString. I am able to detect if the words exist, I'm just not able to get them highlighted.

NSString * wordString = [NSString stringWithFormat:@"%@", [self.myArray componentsJoinedByString:@"\n"]];

self.myLabel.text = wordString;

if ([wordString rangeOfString:@"Base Mix"].location == NSNotFound)
{
    NSLog(@"string does not contain base mix");
}
else
{
    NSLog(@"string contains base mix!");

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:wordString];

    NSString * editedString = [NSString stringWithFormat:@"%lu", (unsigned long)[wordString rangeOfString:@"Base Mix"].location];

    NSRange theRange = NSMakeRange(0, [editedString length]);

    [string beginEditing];
    [string removeAttribute:NSForegroundColorAttributeName range:theRange];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:theRange];
    [string endEditing];

    [self.myLabel setAttributedText:string];
}

This code is closer to the right path. I do see a highlighted character, but it's the very first character in the string and not the words that I have searched for.


Solution

  • You can use the NSUnderlineStyleAttributeName and NSUnderlineColorAttributeName attributes. I think you can use it like this:

    NSRange foundRange = [wordString rangeOfString:@"Base Mix"];
    if (foundRange.location != NSNotFound)
    {
        [wordString beginEditing];
        [wordString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange];
        [wordString addAttribute:NSUnderlineColorAttributeName value:[NSColor redColor] range:foundRange];
        [wordString endEditing];
    }