0

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...

Blue
  • 2,300
  • 3
  • 21
  • 32
  • That can be done easily. But what have you done so far as long as writing code is concerned? – El Tomato Jun 14 '13 at 18:15
  • Look at NSMutableAttributedString : https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsmutableattributedstring_Class/Reference/Reference.html – oiledCode Jun 14 '13 at 18:39

1 Answers1

0

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++;
    }
}
goooseman
  • 619
  • 5
  • 12
  • It doesn't do anything... maybe I'm doing something wrong... I did this: I changed "initWithString: @"Your String"];" with "initWithString: [myTextView string]];"..... "rangeOfString:@"YOURWORD"" with "rangeOfString:word" and at the begin I added "NSString *word = @"button";".... in myTextView there is the word "button" but when I execute this code nothing happens... what am I doing wrong? – Blue Jun 15 '13 at 19:18
  • Ok, I found out what I was missing... I had to add the attrString to my textView... I did it with this and it seams it works good: [[myTextView textStorage] setAttributedString:attrString]; – Blue Jun 15 '13 at 19:58