Variable UITableCellView height with subview

cocoa-touch, iphone, uitableview, user-interface

Solution

The UITableViewDelegate defines an optional method heightForRowAtIndexPath, which will get you started. You then need to use sizeWithFont.

There is some discussion of your precise problem here:

http://www.v2ex.com/2008/09/18/how-to-make-uitableviewcell-have-variable-height/

Text sizing was also discussed in this thread

Problem

I want to create a UITableView with varying row heights, and I'm trying to accomplish this by creating UILabels inside the UITableViewCells. Here's my code so far: ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"EntryCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; } UILabel *textView = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 300, 40)]; textView.numberOfLines = 0; textView.text = [entries objectAtIndex:[indexPath row]]; [cell.contentView addSubview:textView]; [textView release]; return cell; } ``` This gives me 2 lines of text per cell. However, each "entry" has a different number of lines, and I want the UITableViewCells to resize automatically, wrapping text as necessary, without changing the font size. `[textView sizeToFit]` and/or `[cell sizeToFit]` don't seem to work. Here's how I want the UITableView to look: ``` ---------------- Lorem ipsum ---------------- Lorem ipsum Lorem ipsum ---------------- Lorem ipsum Lorem ipsum Lorem ipsum ---------------- Lorem ipsum ---------------- Lorem ipsum Lorem ipsum ---------------- ``` Does anyone know how to do this properly? Thanks.

Original source