如果高亮显示的单词位于行首,则textView中的NSBackgroundColorAttributeName不考虑范围

问题描述 投票:4回答:3

我正在实现“在聊天中搜索”功能,我希望搜索到的单词在消息中突出显示。如标题中所述,问题是,如果单词是一行的第一行(长消息显然是多行),则会突出显示整行而不是单个单词。

[在调试时,我还尝试应用下划线而不是backgroundcolor,并且该下划线是正确的。我不知道问题出在哪里。我的应用聊天是基于JSQMessagesViewController的,因此我一直认为问题可能存在。

[attributedString addAttribute:NSBackgroundColorAttributeName value:backColor] range:wordRange];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle)] range:wordRange];

cell.textView.attributedText = attributedString;

我不发布用于计算范围的代码,因为范围是正确的;事实上,如果我在调试中查看attributedString的预览(将其分配给cell.textView.attributedText),我会看到仅单词突出显示,而不是所有字符串突出显示。

这里是一个例子:Example

ios objective-c nsattributedstring nstextview jsqmessagesviewcontroller
3个回答
3
投票

似乎是系统框架中的错误,因此最好的选择是再增加一行代码,将背景颜色设置回“不变”,紧接在应该更改背景的最后一个字符之后。祝你好运!


0
投票

[查看official documentation后,发现有三种方法具有相似的作用。

  1. setAttributes:range:
  2. addAttribute:value:range:
  3. addAttributes:range:

因此,可能有其他方法,例如setAttributes:range:,可能会解决您的问题。

[attributedString setAttributes:@{NSBackgroundColorAttributeName : backColor}
                          range:wordRange];

cell.textView.attributedText = attributedString;

此外,关于stackoverflow也有类似的问题。也许this answer会为您提供帮助。

NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:(id)backColor.CGColor
                                                             forKey:(id)kCTBackgroundColorAttributeName];
[attributedString addAttributes:stringAttributes 
                          range:wordRange];

cell.textView.attributedText = attributedString;

-1
投票

从结果字符串中查找搜索文本范围,并添加属性范围。尝试下面的代码。

NSString *searchStr = /* SEARCH_STRING */;
NSString *resultText = /* YOUR_RESULT_TEXT */;

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:resultText];

NSString *pattern = [NSString stringWithFormat:@"(%@)", searchStr];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:kNilOptions error:nil];
NSRange range = NSMakeRange(0, resultText.length);

[regex enumerateMatchesInString:resultText options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];

    [attributedString addAttribute:NSForegroundColorAttributeName
                             value:[UIColor redColor]
                             range:subStringRange];
}];
© www.soinside.com 2019 - 2024. All rights reserved.