NSRange,在一个段落中找到一个错误的结果

Mut*_*awe 2 objective-c nsstring nsattributedstring ios nsrange

我写了一个方法来突出显示一个段落NSString中的单词,通过发送一个单词,它完美地工作,直到我遇到这种情况:

当我有这个文字时:

他们的母亲试图在其他地方穿上它们......

当我传递这个词时other,"m other" 这个词正在突出显示,当我走过时,in我得到了"礼服ing".

这是我的代码:

-(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];
    }
Run Code Online (Sandbox Code Playgroud)

我试过使用rangeOfString:options:包含所有选项,但仍然有同样的问题.

请指教

PS: 这是我的代码的来源

Mar*_*n R 7

问题是

NSRange range=[self.textLabel.text rangeOfString:word];
Run Code Online (Sandbox Code Playgroud)

找到文本中第一次出现的单词.更好的选择是按单词枚举文本:

-(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;
}
Run Code Online (Sandbox Code Playgroud)

这种方法具有更多优点,例如即使用引号括起来或用标点符号包围它也会找到一个单词.