1
votes

I have a UITextView inside a UITableViewCell. I am attempting to set the height of the UITextView it based on the content size. Inside my cellForRowAtIndexPath method I have:

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
....
cell.text.text = textString; // cell.text is the UITextView
CGRect frame = cell.text.frame;
frame.size.height = cell.text.contentSize.height;
cell.text.frame = frame;

return cell;

There are other objects on the custom cell, but nothing has constraints. The interesting thing is that when the table view is first loaded, the UITextView does not resize. However, when another cell is loaded by scrolling down or back up, the UITextView resizes to the correct height based on the above code. Why isn't the initial table loading correctly.

The UITextView has a default width and height size. Let me know if I can add more details. I am not implementing heightForRowAtIndexPath, but the testing I am doing has not exceeded the default cell heights so this should not matter anyways.

3
The trouble is you need to know the height of the text view before you can find out the width of the table view cell. After many partially working attempts I ended up taking the table view width and subtracting a hard coded number of pixels depending on [UIDevice currentDevice].userInterfaceIdiom. - Abhi Beckert

3 Answers

0
votes

Did you log the value of cell.text.contentSize.height ? At that moment you don't get the correct value, I think you should set the height on the following UITableView callback:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
0
votes

Try to add [cell.text layoutIfNeeded] before calling cell.text.contentSize

The contentSize will be unknown by the UITextField until it has been drawn. Calling layoutIfNeeded should force the computation of layout size.

0
votes

If finaly made it work with this, try it

cell.text.attributedText = [[NSAttributedString alloc]initWithString:textString];
float textViewWidth      = cell.text.frame.size.width;
[cell layoutIfNeeded];
cell.text.contentSize    = [cell.text sizeThatFits:CGSizeMake(textViewWidth, FLT_MAX)];
[cell.text sizeToFit];