Self-Sizing Cells

suggest change

In iOS 8 Apple introduced the self-sizing cell. Lay out your UITableViewCells with Auto Layout and UITableView takes care of the rest. On iOS 8 through 10, set rowHeight to UITableViewAutomaticDimension. Starting in iOS 11 that is the default. The samples below are Swift 2.

estimatedRowHeight is the estimate used while a self-sizing cell is calculated.

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;
    }  
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents