-1

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Churchill
  • 53
  • 8
  • is the data coming over the network ? What are you currently doing in heightForRowAtIndexPath at this point of time? – Kunal Balani Oct 25 '13 at 17:16
  • have you look at this link.. http://stackoverflow.com/questions/16344400/how-to-set-table-cell-height-dynamically-depending-on-text-label-length – Parab Oct 26 '13 at 06:55
  • Possible duplicate of [Using Auto Layout in UITableView for dynamic cell layouts & variable row heights](https://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights) – Churchill Jun 25 '18 at 13:36

2 Answers2

2

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

ChikabuZ
  • 10,031
  • 5
  • 63
  • 86
0

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.

Community
  • 1
  • 1
adamF
  • 961
  • 2
  • 9
  • 23