Pregunta

I need to change the background color of some particular words in a text that stay in a textView. Something similar to what happens in Firefox when you seearch for a word... So lets say I have a textView with this text

"A man is sitting in front of my porch and another man is calling him"

and I want to change background color to the 2 occurence of the word

"man"

... how could I do that? I know that there is NSAttributedString to do this kind of things but I can not understand how to modify only some particular words... in the examples I found Googling it there were only examples of how to change the first 5 characters or things like this...

¿Fue útil?

Solución

Try this:

NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString: @"Your String"];
NSUInteger count = 0;
NSUInteger length = [attrString length];
NSRange range = NSMakeRange(0, length);

while(range.location != NSNotFound)
{
    range = [[attrString string] rangeOfString:@"YOURWORD" options:0 range:range];
    if(range.location != NSNotFound) {
        [attrString addAttribute:NSBackgroundColorAttributeName value:YOURCOLOR range:NSMakeRange(range.location, [word length])];
        range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
        count++;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top