Question

I made a custom cell, placed a UITextView inside it and I want to change the height of the cell based on the length of UITextView's text length. I know how to statically change the cell height using heightForRowAtIndexPath, but I can't put my head around doing it dynamically, based on content.

I have read about a dozen topics on this forum and on several other, but I didn't find the answer I was looking for.

Any ideas?

Was it helpful?

Solution

in heightForRowAtIndexPath

 float height = [cell.textView.text sizeWithFont:cell.textView.font constrainedToSize:CGSizeMake(cell.textView.frame.size.width, 10000)].height;
 return height;

10000 it's max height of cell, actually you can set max integer value

OTHER TIPS

In your textViewDidChange method, call

[tableView beginUpdates];
[tableView endUpdates];

This will trigger heightForRowAtIndexPath to recalculate all your cell sizes each time the user types a letter. Then in heightForRowAtIndexPath, you can then calculate the necessary size for your cell.

The sizeWithFont method will return the size needed to display the text in a UILabel, which is slightly different than that for a UITextView due to content insets, line spacing, etc. I've used a somewhat hacky solution in the past. If you create a temporary UITextView, set it's text, and use [UIView sizeThatFits:constraintSize] to get the size that will fit all its content within the constraints. (The documentation on this method is a little unclear - take a look at this answer for more info: question about UIView's sizeThatFits)

UITextView *temp = [UITextView alloc] initWithFrame:someArbitraryFrame];
temp.font = DISPLAY_FONT
temp.text = cell.textView.text;
//This gets the necessary size to fit the view's content within the specified constraints
CGSize correctSize = [self.temp sizeThatFits:CGSizeMake(CONSTRAINT_WIDTH, CONSTRAINT_HEIGHT)];
return correctSize.height

In interest of efficiency, you should probably store/lazy-load the temporary textView so that you're not creating a new UITextView for every cell, but rather re-using the same one to calculate height for different text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top