iOS Tips: Dynamic UITextView

With AutoLayout

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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.