0

I found this bit of code here on StackOverflow to highlight a keyword in a UITextView

-(IBAction) highlight:(id) sender{
      NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.text.text];

    NSArray *words=[self.text.text componentsSeparatedByString:@" "];

    for (NSString *word in words) {        
        if ([word hasPrefix:@"@"]) {
            NSRange range=[self.text.text rangeOfString:word];
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        }
    }
    [self.text setAttributedText:string];
    }

For some reason its not getting the range quite right. I can write out a sentence like so:
@Hello this works
and I then can press the button and it will highlight the @Hello bit BUT if I didnt type anything after @Hello it will keep highlighting everything red no matter what. I can only assume its not reading the range of the keywords correctly? Whats going on?

  • Keep highlighting when? As you type more new text after the highlight range was applied by your method? – Wain Jul 30 '13 at 20:53
  • Yep. If theres no more text after a @Perfixed word then everything after the button is pressed will still be highlighted – James Heald Jul 30 '13 at 21:14

1 Answers1

0

That's standard behaviour. Image you changed the font in a text editor and then started typing and the font went back to the standard setting. You will need to code to deal with it. You could detect each edit and reprocess the text. A potential solution is to insert a space character at the end of the text (without highlighting) if you detect this situation while processing. Then if the user chose to delete that space the highlighting would continue.

Wain
  • 118,658
  • 15
  • 128
  • 151