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.
You can use below code which relate to NSAttributed string. works only ios6+
with the help of @user1118321's answer i wrote this function and i would it save some one's time
may it is not very clear code, so i welcome any edit would help
highlight Many words
You can use the
NSUnderlineStyleAttributeName
andNSUnderlineColorAttributeName
attributes. I think you can use it like this:You could create an category method of
NSString
class like thisHow to use it::
I think the part is missing from NSAttributedString. You can try with Three20