4

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.

Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
xeb
  • 191
  • 1
  • 4
  • 12
  • can you add image of your tableview cell constraint? – Hitesh Sep 20 '17 at 10:31
  • One thing you will have to do set your labels up like this: `yourLabel.numberOfLines = 0; yourLabel.lineBreakMode = .byWordWrapping`. Another possibility is to set width constraints on the label, then add text, and then call `yourLabel.sizeToFit()` – Joseph Beuys' Mum Sep 20 '17 at 10:35

4 Answers4

5

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
chirag90
  • 2,211
  • 1
  • 22
  • 37
Kadian
  • 644
  • 4
  • 6
4

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
Anish
  • 61
  • 4
1

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

Community
  • 1
  • 1
Nishant Bhindi
  • 2,242
  • 8
  • 21
1

Swift 4 answer:

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

Please be sure that the constraints are set