How to get a UITableView row height to auto-size to the size of the UITableViewCell?
So assuming I\'m creating the UITableViewCell in Interface Builder, and it hei
As of iOS 8 you have the option to work with self-sizing cells by specifying these options on your table view:
tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableView.automaticDimension
This will work as long as the system can calculate the rows based on existing constraints or content. Take care that if you set automaticDimension then heightForRowAtIndexPath will not be called!
Sometimes with more complex data some cells can be calculated automatically, but others need a specific height calculation logic. In this case you should only set the estimatedRowHeight and then implement cellForRowAtIndexPath with automatic logic for the cells that can work correctly:
// Set the estimated row height in viewDidLoad, but *not* automatic dimension!
override func viewDidLoad() {
// other viewDidLoad stuff...
tableView.estimatedRowHeight = 85.0
tableView.delegate = self
}
// Then implement heightForRowAtIndexPath delegate method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if theAutomaticCalculationWorksForThisRow {
return UITableView.automaticDimension
} else {
// Calculate row height based on custom logic...
let rowHeight = 85.0
return rowHeight
}
}