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?