ios - 当我在 UITextView 委托(delegate)方法 textViewDidChange 中设置属性文本时如何停止光标更改位置

标签 ios objective-c uitextview uitextviewdelegate

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

在textViewDidChange中设置AttributedText时,如何防止光标移动?

- (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];
}

最佳答案

简单地保存和恢复所选范围:

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

关于ios - 当我在 UITextView 委托(delegate)方法 textViewDidChange 中设置属性文本时如何停止光标更改位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914948/

相关文章:

ios - 在 swift 2.2 项目中集成 'PayPal-iOS-SDK'

ios - swift 4 : New Viewcontroller when tapped on a cell with separate class

ios - 有什么方法可以将系统日志记录到iOS中的单独文件中?

ios - UITextView 上的手势动画

iphone - 禁用 UITextView 滚动包含 View ?

ios - NSAttributedString 项目符号列表问题

ios - UIButton:设置 ImageView 的背景(不设置图像)

objective-c - 默认标签栏 View ?

ios - 使用 Segue 从 UIViewController 传输字符串

iphone - 如何禁用横向?