UITextView providing incorrect correction

My UITextView delegate registers a carriage position using the following:

- (void)textViewDidBeginEditing:(UITextView *)textView { CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin; NSLog(@"cursor: %@", NSStringFromCGPoint(cursorPosition)); } 

But the stated position is always inaccurate. In particular, it reports the previous cursor position - for example, if I click once inside the text view at position (x, y), then outside, and then back inside (x2, y2), the second click (x, y) coordinates are registered .

In fact, the selected TextRange is a problem - the previous range is reported.

What am I missing? I do not see another delegate method that I can use instead.

+6
source share
4 answers

The selectedTextRange value will be older only when editing has just begun, it has not changed. When you calculate cursorPostion with the selected text, the old values ​​will return to the old position. Therefore, we need to calculate a new position inside another delegate, which reports after changing the selection. You will receive the correct readings with the code below. Hope this helps.

 -(void)textViewDidChangeSelection:(UITextView *)textView { CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin; NSLog(@"cursor start: %@", NSStringFromCGPoint(cursorPosition)); } 
+4
source

This is pretty crude, but one solution is to introduce a slight delay before reading the method call:

 UITextView *textView = note.object; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ CGPoint cursorPosition = [textView caretRectForPosition:textView.selectedTextRange.start].origin; NSLog(@"cursor: %@", NSStringFromCGPoint(cursorPosition)); }); 
+2
source

Actually, I found another solution.

You can use UIKeyboardDidShowNotification to get the current selectedTextRange, rather than the previous selectedTextRange. Hope this helps!

+1
source

I had the same problem, but with UIKeyboardWillShowNotification . Adding a little delay helped in my case:

 func keyboardWillAppear(notification: NSNotification!) { dispatch_after_delay(0.01) { if textView.selectedTextRange { // at this point range is correct } } } func dispatch_after_delay(delay:NSTimeInterval, queue: dispatch_queue_t = dispatch_get_main_queue(), block: dispatch_block_t) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), queue, block) } 
+1
source

Source: https://habr.com/ru/post/976466/


All Articles