以下代码将 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/