How to change tableview cell height according to label text swift?

Viewed 7979

Using a UITableView in Swift, could someone please help me automatically change the height of the cell based on the label, picture, and description please?

I want to dynamically change the cell size as the label text increases. i have already applied autolayout on the labels.

4 Answers

Considering you have already applied constraints on the label. And also set your number of lines to 0. And then paste the following code in viewDidLoad method

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

If the code below doesnt work in method viewDidLoad doesn't work instead add the code below in method ViewWillAppear

tableView.estimatedRowHeight = 60.0// the estimated row height ..the closer the better
tableView.rowHeight = UITableView.automaticDimension

plus :

  1. The constrain should atleast define the width ,top spacing and bottom spacing not the height constrain.
  2. In attributes set lines to 0

For making the cell auto sizeable, you need to do two things:

  1. Bottom space and top space constraints will push the cell size as needed. number of lines of label is 0.

  2. In your viewDidLoad() method add self.tblList.estimatedRowHeight = 50.0 self.tblList.rowHeight = UITableViewAutomaticDimension

Swift 4 answer:

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableView.automaticDimension

Please be sure that the constraints are set

Related