如果突出显示的单词是一行的第一行,则 textView 中的 NSBackgroundColorAttributeName 不考虑范围

Chr*_*ini 11 objective-c nstextview nsattributedstring ios jsqmessagesviewcontroller

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

在调试时,我也尝试应用下划线而不是背景色,下划线是正确的。我无法弄清楚问题出在哪里。我的应用程序的聊天基于JSQMessagesViewController,所以我认为问题可能出在那里。

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

cell.textView.attributedText = attributedString;
Run Code Online (Sandbox Code Playgroud)

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

下面是一个例子:
例子

Ada*_*ski 7

似乎是系统框架中的一个错误,所以最好的办法是再添加一行代码,将背景颜色设置回“未更改”,直接在应更改背景的最后一个字符之后。祝你好运!