How do I size a UITextView to its content on iOS 7?

I favor this minimal code change: Just add these two lines after addSubview and before grabbing the height of the frame

...
[scrollView1 addSubview: myTextView];

    [myTextView sizeToFit]; //added
    [myTextView layoutIfNeeded]; //added

CGRect frame = myTextView.frame;
...

This is tested backwards compatible with iOS 6. NOTE that it shrink-wraps the width. If you’re just interested in the height and have a fixed width, just grab the new height but set the original width, and it works just as before on both iOS 6 and 7.

(Speculation: it does size to fit on iOS 7 as well, but the layout is updated later or in a separate thread, and that this forces the layout immediately so that its frame is updated in time for using its height value a few lines later in the same thread.)

NOTES:

1) You might or might not have implemented the outer container resize this way. It does seem to be a common snippet, though, and I’ve used it in my projects.

2) Since sizeToFit seems to work as expected on iOS 7, you likely don’t need the premature addSubView. Whether it will still work on iOS 6 then is untested by me.

3) Speculation: The extra layoutIfNeeded mid-thread might be costly. The alternative as I see it is to resize the outer container on the layout callback (fired or not depending on if the OS decides whether layout is needed or not) where the outer container resize will cause another layout update. Both updates might be combined with other layout updates to be more efficient. If you do have such a solution and you can show that it is more efficient, add it as answer and I’ll be sure to mention it here.

Leave a Comment