Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop cursor changing position when I setAttributedText in UITextView delegate method textViewDidChange

The following code changes "test" in the textView's string to red color but it also has the effect of moving the cursor to the end of the text block when textViewDidChange is called (Aka when any text editing is made which is very annoying).

How can I prevent the cursor moving when I setAttributedText in textViewDidChange?

- (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];
}
like image 497
KarlHarnois Avatar asked Jan 21 '16 03:01

KarlHarnois


1 Answers

Simply save and restore the selected range:

NSRange selectedRange = self.textView.selectedRange;
self.textView.attributedText = string;
self.textView.selectedRange = selectedRange;
like image 97
rmaddy Avatar answered Nov 07 '22 08:11

rmaddy