0

I need to set UITableViewCell dynamic height based on it's content.

Here is my demo image:

enter image description here

In this to label which have dynamic content so based on that label content my cell height should change..

I get the constraint error. In this cell two UILabel is available and both have dynamic content size. (I already make the demo with auto resizing cell with only one label.) But in this cell two label are there. So error is xcode suggest me to give Y POS or Height to label, but I already set top constraints. (4 side constraints with label line set to 0 Zero) But still it's fails. I also try with this code

self.tableView.estimatedRowHeight = 250.0;
self.tableView.rowHeight = UITableViewAutomaticDimension;

Here is my demo code

NiravS
  • 1,144
  • 1
  • 12
  • 24

5 Answers5

7

Look at the screenshot of my output. For both the labels , you should give all the four constrains and you have to change the heights of both the labels priority to 750 & set the hugging and resistance priority to 1000. Then you have to change the number of lines to 0 in storyboard

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

        return 250

    }

enter image description here

Catherine
  • 654
  • 5
  • 15
0

Add this code into viewDidLoad() method:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44
Vlad Khambir
  • 4,313
  • 1
  • 17
  • 25
0

In Swift 3, Use

func tableView(_ tableView: UITableView,estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {

    return HEIGHT // Maximum cell height
}

In table view cell, Set dynamic height constraint to the text view (Greater than or equal) - Maximum text view height

Lineesh K Mohan
  • 1,702
  • 14
  • 18
0

I found the problem. After setting text to UILabel, it doesn't still set correct height frame to its content. In cellForRowAt, just add this:

//these make height frame both of labels became correct

cell.lbName.sizeToFit()
cell.lbAge.sizeToFit()

// update cell layout
cell.layoutIfNeeded()
T.Nhan
  • 188
  • 1
  • 9
-1

Have a look at the UITableViewDelegate function tableView(_:heightForRowAt:). It’ll work in your case if you are able to calculate the height for a given index path.

Tom E
  • 1,530
  • 9
  • 17