daspianist daspianist - 1 month ago 15
Swift Question

Configuring TableView with automatic cell height results in no cells displayed

My goal is to use

to show cells with dynamic heights in my TableView. At the moment, no cells show up in my tableview after enabling

Here is my current configuration:

  1. I am using a custom cell class, called

  2. FeedCell
    has a view called
    , which has been configured as such where all sides are pinned. enter image description here

  3. I have also tried to pin the
    of the cell, but was unable to: enter image description here

  4. Lastly, I have the following in

    self.tableView.rowHeight = UITableViewAutomaticDimension

    self.tableView.estimatedRowHeight = 112.0

(I also deleted the default function
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

If I don't use
, the cells appear normally, confirming that the data is fed into the tableview correctly.

What am I doing wrong? Any pointers much appreciated.

Answer Source

I think your constraints are ambiguous. You are asking UIKit to automatically size your cell (UITableViewAutomaticDimension), but the "Foreground Container View" does not have a defined height...it is only constrained to the cell itself (which also doesn't have a defined height!).

So you probably have some kind of ambiguous constraint warning in the console since the system doesn't know what to do, or it's possible your "Foreground Container View" is defaulting to a height of 0.0 meaning your table cell height is about 10.5 (0.0 + your constrained spacing). You didn't include a screenshot of what actually shows in the simulator, so I'm just guessing.

Give your "Foreground Container View" some content or explicitly constrain it's height to something you will be able to see (ex. 200px). Also I recommend you give it a background color so you can actually see it's height on your screen.

To get automatic cell sizing with actual cell content, you should constrain views (labels, images, whatever else) inside your "Foreground Container View" (or if you want, inside the cell's content view directly).

There must be both a top spacing and bottom spacing constraint between the anticipated tallest subviews (labels, images, etc.) and the container.