Search code examples
iosswiftautolayoutinterface-buildernslayoutconstraint

Auto-Layout: "center horizontally" does not seem to resolve inequality ambiguity of width/x-position, within a UICollectionViewCell


Suppose I have a UIView called inner, which is a subview of a UICollectionViewCell's Content View in Interface Builder. The collection view uses flow layout and uses collectionView(_:layout:sizeForItemAt:) to determine the size of the cell at layout time.

I want inner to take up the entire width of the cell, but if the cell's width is less than 6 then inner should be centered horizontally in the cell and have a width of 6 (clipsToBounds is false on the cell and the cell's Content View).

The horizontal constraints below "should" be sufficient to do this, but Interface Builder shows me two errors:

  • Missing Constraints: Need constraints for: X position, width
  • Inequality Constraint Ambiguity: inner.leading <= leading

Proposed horizontal constraints:

  1. inner.centerX = centerX
  2. inner.trailing >= trailing
  3. inner.leading <= leading
  4. inner.width >= 6

Why isn't this enough? Does it have something to do with the sizeForItemAt:?


Solution

  • Interface Builder's complaints might be spurious. It's better to run the app and see what happens in the View Debugger. I was able to achieve your goal like this:

    • inner leading <= superview leading

    • inner trailing >= superview trailing

    • inner centerX == superview centerX

    • inner width == 6 at a priority of 999

    The results look right. The view debugger didn't complain, so I presume my settings are valid.