Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView with contentInset: text entry causes content-jumps

Tags:

uitextview

I have a UITextView for letting the user enter multi-line texts. When the text exceeds the size of the TextView it needs to start scrolling.

When the onscreen keyboard pops up I set the height of the keyboard as a bottom-contentInset to the TextView to mitigate the issue of the keyboard overlapping the TextView. However, when the contentInset is bigger than the height of the TextView's frame its content starts jumping when trying to enter text. The text-entry caret jumps out of view and with every keystroke de entire text content jumps up and down, essentially making text entry impossible.

This can be reproduced without any code, so it's not a code bug but a component behavior issue:

  • create a view with a viewcontroller, disable autolayout.
  • put a UITextView on the View (you can leave the lorem-ipsum text in)
  • make the UITextView height 400
  • add a contentInset of 500 to the bottom of the UITextView
  • run on a device or in the simulator

As soon as you touch the UITextView to give it focus to start typing everything jumps up and the text-entry cursor/caret moves out of view and starts jumping erratically.

What am I doing wrong, or how can this be avoided?

like image 915
Bram Bos Avatar asked Oct 17 '25 18:10

Bram Bos


1 Answers

Answering my own question:

Apple's documentation recommends using the contentInset property for keeping the keyboard from overlapping the key parts of your UI. However, as I found out above this does not work for UITextViews...

Instead you should use the textContainerInset property! This behaves as expected.

- (void)keyboardWasShown:(NSNotification*)aNotification {

    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake( 0, 0, kbSize.height, 0 );
    textView.textContainerInset = contentInsets;
    textView.scrollIndicatorInsets = contentInsets;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    textView.textContainerInset = contentInsets;
    textView.scrollIndicatorInsets = contentInsets;
}
like image 144
Bram Bos Avatar answered Oct 22 '25 05:10

Bram Bos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!