iOS Self-Sizing Cells


Example

In iOS 8 Apple introduced the self sizing cell. Layout your UITableViewCells with Autolayout explicitly and UITableView takes care of the rest for you. Row height is calculated automatically, by default rowHeight value is UITableViewAutomaticDimension.

UITableView property estimatedRowHeight is used when self-sizing cell is calculating.

When you create a self-sizing table view cell, you need to set this property and use constraints to define the cell’s size.

-- Apple, UITableView Documentation

self.tableView.estimatedRowHeight = 44.0

Note that the tableView's delegate's heightForRowAtIndexPath is unnecessary if you want to have a dynamic height for all cells. Simply set the above property when necessary and before reloading or loading the table view. However, you can set specific cells' height while having others dynamic via the following function:

Swift

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    switch indexPath.section {
    case 1:
        return 60
    default:
        return UITableViewAutomaticDimension
    }
}

Objective-C

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  switch (indexPath.section) {
      case 1:
        return 60;
      default:
        return UITableViewAutomaticDimension;
    }  
}