0

UICollectionView Flow Layout Inner Constraints

I have a UICollectionView that uses flow layout and dynamic-width cells defined in a xib. The xib has constraints on all sides of a stack view that contains a dynamic label and a static image. These constraints should change based on the margins provided in configureCell(cellData:, padding:), which is called on cellForItemAt and sizeForItemAtIndexPath datasource/delegate methods. Unfortunately, the sizes returned by systemLayoutSizeFitting() are incorrect if I change the constraints to something else in configureCell(cellData:, padding:).

UICollectionViewCell xib subclass

I've tried setNeedsLayout(), layoutIfNeeded(), setNeedsUpdateConstraints(), updateConstraintsIfNeeded() in every combination I can think of. I have also tried these solutions without success.

How does one update constraints inside a UICollectionViewCell and have it size properly in collectionView(collectionView:, layout:, sizeForItemAtIndexPath:)?

UICollectionViewDataSource:

private var _sizingViewCell: LabelCollectionViewCell!

//registers and init's sizing cell...

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
    _sizingViewCell.configureCell(self.cellData[indexPath.row], padding: defaultItemPadding)
    var size = _sizingViewCell.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
    return size
}

UICollectionViewCell subclass:

func configureCell(_ cellData: LabelCollectionCellData, padding: UIEdgeInsets? = nil) {
    removeButton.isHidden = cellData.removable
    if let padding = padding {
        leadingPaddingConstraint.constant = padding.left
        topPaddingConstraint.constant = padding.top
        trailingPaddingConstraint.constant = padding.right
        bottomPaddingConstraint.constant = padding.bottom

        contentStackView.spacing = padding.left
    }
}
Albert Bori
  • 9,324
  • 9
  • 47
  • 76

1 Answers1

0

The problem turned out to be operator error.

I was giving configureCell(cellData:, padding:) a different padding in:

collectionView(_ collectionView:, cellForItemAt indexPath:)

than I was giving in:

collectionView(collectionView:, layout collectionViewLayout:, sizeForItemAtIndexPath indexPath:)

Which caused the views to not display correctly.

Albert Bori
  • 9,324
  • 9
  • 47
  • 76