Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top