Self-sizing Table View Cells

Hi @fschnek! You can do that pretty easily… Start by removing the following lines:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140

You can then implement the following UITableViewDelegate functions:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if shouldUseSelfSizingCells(for: indexPath) {
        return UITableViewAutomaticDimension // will ask for the estimatedHeightForRowAt
    } else {
        return 44 // just fix the cell to 44pt
    }
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    if shouldUseSelfSizingCells(for: indexPath) {
        return 44
    } else {
        return 0 // this will never be called
    }
}

func shouldUseSelfSizingCells(for indexPath: IndexPath) -> Bool {
    // Some real check here based on the IndexPath
    return (indexPath.row % 2) == 0
}
1 Like