Auto Growing UITableViewCells with Static Cells

17. Dezember 2016 code 0

Just a small iOS development thing I stumbled upon.

You can have auto growing cells in a UITableView with Auto Layout really easy by setting the estimated height and the row height:

override func viewDidLoad() {
  super.viewDidLoad()

  tableView.estimatedRowHeight = 44.0
  tableView.rowHeight = UITableViewAutomaticDimension
}

I am using this for an edit screen with an UITextView in an UITableViewCell. If you disable scrolling for the text view and set up your auto layout constraints correctly this works fine. Unless you are designing your table view cells as static cells in Interface Builder! Here the automatic row height doesn’t seem to apply. But don’t worry, the fix is quite simple! Just use the table view delegate methods instead of the properties for setting the (estimated) row height and it works like a charm:

// MARK: - Table View Delegate
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
  return 44.0
}
    
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  return UITableViewAutomaticDimension
}