【问题标题】:How to stop cursor changing position when I setAttributedText in UITextView delegate method textViewDidChange当我在 UITextView 委托方法 textViewDidChange 中 setAttributedText 时如何停止光标更改位置
【发布时间】:2016-04-27 04:17:23
【问题描述】:

以下代码将 textView 字符串中的“test”更改为红色,但它也具有在调用 textViewDidChange 时将光标移动到文本块末尾的效果(也就是当进行任何文本编辑时,这很烦人)。

当我在 textViewDidChange 中 setAttributedText 时如何防止光标移动?

- (void)textViewDidChange:(UITextView *)textView {

    NSString* currentString = self.textView.text;
    NSMutableAttributedString* string = [[NSMutableAttributedString alloc]initWithString:currentString];
    NSArray *words=[currentString componentsSeparatedByString:@" "];

    for (NSString *word in words) {
        if ([word isEqualToString:@"test"]) {
            // change color
            NSRange range=[currentString rangeOfString:word];
            [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
        }
    }

    // assign new color to textView's text
    [self.textView setAttributedText:string];
}

【问题讨论】:

  • 仅供参考 - 您的代码只会找到第一次出现的“test”。
  • 是的,这是我想要解决的另一件事:P

标签: ios objective-c uitextview uitextviewdelegate


【解决方案1】:

只需保存和恢复所选范围:

NSRange selectedRange = self.textView.selectedRange;
self.textView.attributedText = string;
self.textView.selectedRange = selectedRange;

【讨论】:

  • 如果您的字符串长于 textField 可以显示并将光标移动到开头,那将不起作用。当您键入文本时,光标停留在一个位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
相关资源
最近更新 更多