iOS TextView inside ScrollView caret misplacement in new line

Viewed 312

I have the following layout that is a well know approach to use a TextView inside a ScrollView.


enter image description here


It works really great overall but there is a small issue that annoys me a lot.


enter image description here

Look at the caret. When inserting a new line autolayout won't update. It only update the constraints when new characters are added and suddenly the line shows up properly again. For context this works really great when using only TextViews without scrollViews so im wondering if there is something more i need to do manually to emulate that behaviour.

Right now im triggering a view.layoutIfNeeded() on the textViewDidChange delegate to solve the issue but it feels overkill to me.

Thanks in advance.

1 Answers

Good question!

Use this in your textViewDidChange method:

- (void)textViewScrollToCarretIfNeeded:(UITextView *)textView {
    CGRect caretRectInsideTextView = [textView caretRectForPosition:textView.selectedTextRange.start];
    CGRect caretRectInsideScrollView = [self.scrollView convertRect:caretRectInsideTextView fromView:textView];
    [self.scrollView scrollRectToVisible:caretRectInsideScrollView animated:YES];
}

you can convert this to swift using online services.

Related