UITableViewCell, UITextView with dynamic height

WrightsCS picture WrightsCS · Feb 3, 2011 · Viewed 16.1k times · Source

I need to make a UITableViewCell that holds alot of text. I know I can add a UITextView to my cell, but each entry will not have the same amount of text.

I know I can control the height of the UITableViewCell with: -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath, but thats not really what I am looking for.

Scenario 1:

 ---------------
| First Cell    |
 ---------------
 ---------------
| Second Cell   |
| with some     |
| text.         |
 ---------------
 ---------------
| Third Cell    |
 ---------------

Scenario 2:

 ---------------
| First Cell    |
 ---------------
 ---------------
| Second Cell   |
| with some     |
| more text and |
| an unknown    |
| cell height.  | 
 ---------------
 ---------------
| Third Cell    |
 ---------------

Answer

Anh picture Anh · Feb 3, 2011

Use UILabel for your cell text. You can then use sizeWithFont:constrainedToSize: to calculate the height of that UILabel within each cell. For example:

#define PADDING 10.0f

- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = [self.items objectAtIndex:indexPath.row];
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];

    return textSize.height + PADDING * 3;
}