1

这是一个UITextView,我在上面放了很长的章节(我想让它像一本书一样。),当我按下一个词超过2秒时,(我在这里设置了一个长手势),然后这个词将被突出显示(下面的代码可以成功高亮这个词,但也会触发一些我需要消除的副作用),那么故事就来了:

代码如下:

   NSMutableAttributedString *attrStr = [self.contentTextView.attributedText mutableCopy];
   [attrStr addAttribute:NSBackgroundColorAttributeName value:[UIColor grayColor] range: _wordToSearchRange ];
   self.contentTextView.attributedText = attrStr;

到目前为止,我调试了代码,最后瞄准了这一行:

   self.contentTextView.attributedText = attrStr; 

这导致我的 textView 滚动到顶部(不停留在当前单词位置),这是合理的,因为此操作类似于刷新 textView 并为其设置全新的内容。但是有没有其他方法可以在 textView 中设置特定的单词范围而不会导致这种情况?

任何帮助都会很棒!多谢!

4

1 回答 1

0

由于您正在编辑现有文本,因此不应全部替换。您需要创建属性字典并将其添加到属性文本中:

NSMutableDictionary* attributes; //set the wanted attributes
NSRange range; //set the right range

[_contentTextView.textStorage beginEditing];
[_contentTextView.textStorage addAttributes:attributes range:range];
[_contentTextView.textStorage endEditing];
于 2015-08-05T06:12:12.570 回答