Making a UITableViewCells height dynamic based on its content is obtained by doing the following:
- Make sure the content of your UITableViewCell is constrained such the dynamic content is pinned to both the top and bottom of the cell.
A contrived example cell:
class Cell: UITableViewCell {
let label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Allows your text to expand multiple lines
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(label)
// Constrains a UILabel to the edges of the UITableViewCells content view
label.topAnchor.constraint(equalTo: commentBox.topAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: commentBox.bottomAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: commentBox.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: commentBox.trailingAnchor).isActive = true
}
}
As you have above, return UITableViewAutomaticDimension
from func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
To help your UITableView compute the dynamic height, its recommended to return an estimated size you think your cell is going to be.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat