【问题标题】:Color the specific range of word by NSMutableAttributedString in a UITextView cause UITextView scroll to the top?在 UITextView 中通过 NSMutableAttributedString 为特定范围的单词着色,导致 UITextView 滚动到顶部?
【发布时间】:2015-08-05 05:03:37
【问题描述】:

这是一个 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 中设置特定的单词范围而不会导致这种情况?

任何帮助都会很棒!非常感谢!

【问题讨论】:

    标签: ios objective-c uitextview nsmutableattributedstring contentoffset


    【解决方案1】:

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

    NSMutableDictionary* attributes; //set the wanted attributes
    NSRange range; //set the right range
    
    [_contentTextView.textStorage beginEditing];
    [_contentTextView.textStorage addAttributes:attributes range:range];
    [_contentTextView.textStorage endEditing];
    

    【讨论】:

    • thx 兄弟,我只是试试这个,它会导致相同的结果 - textView 将滚动到顶部..
    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    相关资源
    最近更新 更多