Ive written a method to highlight a word within a paragraph by sending it an NSString of that word, it was working perfectly until i faced this scenario:

When i have this text:

Their mother has tried dressing them in other ...

When I'm passing the word other, the word "mother" is being highlighted, also when I'm passing in i got "dressing".

Here is my code:

-(void)setTextHighlited :(NSString *)txt{
    NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.textLabel.text];

    for (NSString *word in [self.textLabel.text componentsSeparatedByString:@" "]) {

        if ([word hasPrefix:txt]) {
            NSRange range=[self.textLabel.text rangeOfString:word];
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    }

I've tried to use rangeOfString:options: with all of its options, but still have the same problem.

Please advice

PS: This is the source of my code

有帮助吗?

解决方案

The problem is that

NSRange range=[self.textLabel.text rangeOfString:word];

finds the first occurrence of the word in the text. A better option is to enumerate the text by words:

-(void)setTextHighlited :(NSString *)txt{

    NSString *text = self.textLabel.text;
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:text];

    [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                             options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                 if ([substring isEqualToString:txt]) {
                                     [string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:substringRange];
                                 }
                             }];
    self.textLabel.attributedText = string;
}

This method has more advantages, for example it will find a word even if it is enclosed in quotation marks or surrounded by punctuation.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top