iOS Tips: Dynamic UITextView

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.

Designer, iOS/macOS Developer; rider of motorcycles

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