【问题标题】:NSRange, Find a word within a paragraph getting wrong resultsNSRange,在段落中查找一个单词得到错误的结果
【发布时间】:2013-11-28 07:43:31
【问题描述】:

我编写了一个方法来突出段落中的一个单词,方法是向它发送该单词的NSString,在我遇到这种情况之前它工作得很好:

当我有这段文字时:

他们的母亲曾尝试给他们穿其他衣服......

当我传递单词other 时,单词“mother”被突出显示,当我传递in 时,我得到了“dressing”。

这是我的代码:

-(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];
    }

我已尝试将 rangeOfString:options: 与它的所有选项一起使用,但仍然遇到同样的问题。

请指教

PS:This is the source of my code

【问题讨论】:

  • NSRegularExpression 可能是解决方案。范围返回是rangeOfString 的正常行为。
  • 任何例子\
  • @HashmatKhalil 我需要使用 NSRange 而不是 NSPredicate 的解决方案!
  • 有点冗长,但有一些使用 NSRegularExpression 的例子。无论如何,Tut 似乎适合你正在做的事情。

标签: ios objective-c nsstring nsattributedstring nsrange


【解决方案1】:

问题是

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

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

-(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;
}

这种方法有更多的好处,比如它会找到一个单词,即使它是 用引号括起来或用标点符号括起来。

【讨论】:

    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多