Search code examples
iosuitableviewautolayoutnslayoutconstraint

Layout errors when pinning UIView edges to UITableViewCell contentView


Got a problem here which is driving me crazy.

In a storyboard I have a table view in a layout and I'm trying to pin the leading, top, trailing and bottom constraints of a UIView to the prototype cell's content view. Straightforward enough.

Whenever I do this I get these layout errors for the UIView in Xcode:

"Need constraints for: X position, width"

"Need constraints for : Y position, height"

Problematic UIView

View hierarchy

Constraints on that view (Superview is contentView):

UIView constraints

In the storyboard I have the following set on the table view:

  • Row Height: automatic
  • Estimate (row height): 50

Table view settings

And on the table view cell:

  • Row Height: 50

Table view cell settings

I've seen a few SO posts and other walkthroughs that state that pinning the edges is what to do, and as I understand Auto Layout, I've provided the necessary constraints and info.

How can I fix this?

(BTW: I'm running Xcode 11.3.1.)


Update: The cells of this table view will be fixed height. I'm looking for the cell to provide the height for its content.


Solution

  • It turns out I had the table view and cell constraints and settings configured properly; the problem was further up the view hierarchy.

    The table view was placed in a vertical stack view, and that stack view's Alignment property was set to center (for the benefit of other views in the stack). This was causing issues for Auto Layout in calculating the width of the table view.

    The solution here was to add an Equal Widths constraint from the table view to the stack view. Et voila! The errors on the UIView within the table view cell's content view disappeared.

    Fixer constraint