6

By default, the UITextView's contentView becomes scrollable when there is too much text to fit into the textview based on it's height.

I'd like to disable this and instead, update the height of the UITextView to fit in the text. The reason I'm doing this is because I'm adding the UITextView as a subview of a UIScrollView which should handle the scrolling, much like in the native Mail app (when you enter text, the whole view scrolls up, not just the textview.

Anyone got some ideas / has run into the same problem before?

2 Answers 2

20

It is very simply done like this:

CGRect frame = textView.frame;

frame.size = textView.contentSize;

textView.frame = frame;

This should set the height of the textview to appropriately fit all of its content.

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

3 Comments

That's great. I had to add a few things to it which I'll post in a new answer because of the comment formatting.
This works fine in iOS5 but for some reason on iOS4 the cursor keeps wanting to drift outside the bounds of the view.
have bug on iPhone 6plus.
9

Few little changes:

-(void)textViewDidChange:(UITextView *)textView {

    CGFloat fontHeight = (textView.font.ascender - textView.font.descender) + 1;

    CGRect newTextFrame = textView.frame;
    newTextFrame.size = textView.contentSize;
    newTextFrame.size.height = newTextFrame.size.height + fontHeight;
    textView.frame = newTextFrame;
}

Adding the font height gives room for the autocorrection box when you spell something incorrectly.

The UITextView should also be set to not scroll:

[aTextView setScrollEnabled:NO];

4 Comments

How does this handle scrolling the view to the cursor?
You can also set textView.clipsToBounds = NO; to make the autocorrection box not get clipped.
It gets clipped by the keyboard, not by the text view.
as per documentation of textViewDidChange: The text view calls this method in response to user-initiated changes to the text. This method is not called in response to programmatically initiated changes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.