101
votes

Despite having set constraints to all elements, including the vertical ones needed for the cell to calculate its height, auto-layout seems to be ignored: all cells are squeezed.

Here's a screenshot of the result and of the constraints in the storyboard. enter image description here

enter image description here

In the VC that holds the tableView, here's the code in viewDidLoad:

tableView.estimatedRowHeight = 120.0
tableView.rowHeight = UITableViewAutomaticDimension

Commenting out the second line gives cells with a height of 120.0 but Autolayout is ignored as well.

Thanks


Update

To simplify the interface, I've left a single label with, as constraints:

  • Leading space to superview
  • Top space to superview
  • Fixed width and height (100 & 100)
  • Bottom space to container margin to make sure that the cell has all vertical constraints to determine its height

And with this simplified interface, auto-layout is still not taken into account, which hints me that the problem did not come from badly set constraints.

In the Size Inspector, the row height is set on 120 and Custom is checked. The cell has the right custom class, the cell reuse identifier is correct.


Update: solution found

This was a simple mistake, see my answer below.

2
Check your debug terminal - are there any NSLayoutConstraint logs in there suggesting something isn't working as expected?Matthew Hallatt
Nothing appears in the debug terminal @MatthewHallatt, thank you.Kqtr
@Kqtr try commenting these two lines and then run it normally once to check is there any change?Tushar Sharma
@TusharSharma Commenting out the two lines has the same effect as commenting out the rowHeight line only: the cell has a height of 120.0, but auto-layout doesn't work.Kqtr
Does interface builder show any constraints as missing or ambiguous? Check for the little yellow or red exclamation mark.Matthew Hallatt

2 Answers

265
votes

Auto-layout was ignored because both the prototype cell AND the UIView of the cell had been given the custom cell class in IB.

Setting the UIView back to UIView class solved the problem.

just to be über clear

-3
votes

I think the problem is that you are implementing :

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

 return x
}

You need to remove this function inorder for the tableview to calculate its automatic height for cells.