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:).
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
}
}

