Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic UITableViewCell not resizing according to the content

enter image description here

Senario A: If I set the label content in cellForRowAtIndexPath, the cell correctly get resized.

Senario B: If I change the text content in custom action in cell, the cell sized does not get changed.(I do call setNeedsLayout + layoutIfNeeded)

How to fix this?

EDIT:

1) I have set, myTableView.estimatedRowHeight = 71.0 myTableView.rowHeight = UITableViewAutomaticDimension

2) I have correctly added auto layout constraints.

like image 675
Thilina Chamath Hewagama Avatar asked Dec 27 '16 11:12

Thilina Chamath Hewagama


4 Answers

I was running into this issue, and my problem was that I was constraining the content to self (the UITableViewCell) and not to self.contentView (the contentView OF the cell). Hope this helps someone else who has built their cells all in code!

like image 162
ccwasden Avatar answered Oct 17 '22 06:10

ccwasden


In my case, the cell's custom size was enabled:

enter image description here

like image 31
StrawHara Avatar answered Oct 17 '22 04:10

StrawHara


After you change the text of the cell, just reload that particular cell or simply call mainTableView.reloadData().

To reload that cell-

//indexPath is indexPath of cell you just changed label of
mainTableView.reloadRows(at: indexPath, with: .automatic)
like image 40
Rikh Avatar answered Oct 17 '22 05:10

Rikh


In my case, in the same cell I had an imageView in the top left corner with a "center vertically in container" constraint, and a "top space container" constraint.

Obviously to satisfy this two constraint the cell must have an height equal to:

(height of the imageView / 2) + (length of the top space container constraint).

This height is not enough to fit the label text, so my label had only 1 line visible.

After I have deleted the imageView top constraint all went to the right place, in my case i wanted the image to be centered, if the image had to stay in the top left corner I had to take off the "center vertically in container" constraint.

I hope this can help someone.

like image 3
Federico Arvat Avatar answered Oct 17 '22 04:10

Federico Arvat