iOS Tips: Dynamic UITextView

With AutoLayout

Paul Jackson
Dec 16, 2013 · 1 min read

A UITextView does not automatically resize in a UIView when you use AutoLayout alone; code is required—specifically, code similar to this:

CGSize size = self.textView.contentSize;
self.textViewHeightConstraint.constant = size.height;

For this approach to work it is important that you place these lines in the right place—in the viewDidAppear method—and that you have created an outlet for a height constraint on the target UITextView—called textViewHeightConstraint in the example above.

To achieve the same effect with a UITableViewCell the approach is the same; but this time you enumerate through the visible cells and then set the content height value for the constraint:

UITableView *table = self.someTable;
for (SomeCell *cell in table.visibleCells) {
float height = cell.textView.contentSize.height;
cell.textHeightConstraint.constant = height;
[cell.textView sizeToFit];
}

Note the call to sizeToFit in this code; calling sizeToFit ensures that the container for the UITextView resizes correctly—otherwise the bottom of your text may be clipped.

I have created a very simple code example that you can use if you want to see this approach in action.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store