How to create static cells with dynamic cell heights with Swift
For Swift 3
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
UILabel:
Set numberOfLines = 0
via programmatically or set lines to zero in attributes inspector of the UILabel
.
UITextView:
Let's select your text view and uncheck the scrolling enabled like as below image.
Add the below code to your view controller:
Swift 5:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Swift 2.2:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
All you have to do is set proper AutoLayout
inside the cell
, so the height increases based on the length of the description text.
Then you need to set the following in your viewDidLoad
tableview.rowHeight = UITableViewAutomaticDimension
tableview.estimatedRowHeight = 44
Please note: you need to set the numberOfLines
of UILabel
to 0