Joris Kluivers

I like to build software.

Multi-line UITableViewCell

On multiple occasions I needed to display multi-line text in a UITableViewCell. For example to display an address I would prefer to use a single cell with multiple lines of text, like the Contacts app does.

Previously I would always create custom UITableViewCell subclasses. Thankfully Ahmed Abdelkader found out how to configure a default cell to display multi-line text without any subclassing.

To create a cell similar to the one in the Contacts app:

1
2
3
4
5
6
7
8
9
10
static NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
 cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2
     reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = @"work';
cell.detailTextLabel.text = @"Kosterijland 42\n3981 AJ Bunnink\nNetherlands";
cell.detailTextLabel.numberOfLines = 3;
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;

Make sure the table view also knows about the correct height.

1
2
3
4
5
6
- (CGFloat) tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (/* my address row */) {
        return  (44.0 + (numberOfLines - 1) * 19.0);
    }
    return 44.0;
}

The formula 44.0 + (numberOfLines - 1) * 19.0 is derived from measurements on cells with different number of lines in the Contacts application.

(via)