3

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.

2
  • you can reduce the height Constraints of your UITextView when Editing . Commented Jul 11, 2017 at 10:52
  • The TextView doesn't have a height constraint but similarly i can work with reducing the bottom margin or something when editing, but this approach feels very hacky to me too :/ Commented Jul 11, 2017 at 11:03

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried this approach, but it does not work. And here is the code converted to swift 5: func textViewScrollToCarretIfNeeded(textView: UITextView) { let caretRectInsideTextView = textView.caretRect(for: textView.selectedTextRange!.start) let caretRectInsideScrollView = scrollView.convert(caretRectInsideTextView, from: textView) scrollView.scrollRectToVisible(caretRectInsideScrollView, animated: true) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.