UITableView Self-sizing cells (Row height automatic calculation using UITableViewAutomaticDimension)
--
A simple, widely-used, yet very powerful view that can present data in a list form using rows and a single column. Users may scroll vertically through the items in a table view, and optionally manipulate and select content.
Self-Sizing Cells
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; }
}