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.

Javier Cadiz
  • 12,326
  • 11
  • 55
  • 76
  • you can reduce the height Constraints of your `UITextView` when Editing . – Dhiru Jul 11 '17 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 :/ – Javier Cadiz Jul 11 '17 at 11:03

1 Answers1

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.

Yaroslav Luchyt
  • 223
  • 3
  • 8
  • 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) }` – Samuël Apr 15 '19 at 10:13