修改底层布局约束时,UICollectionViewCell子类的大小不正确

时间:2017-05-26 00:39:35

标签: ios xcode uicollectionview autolayout uicollectionviewcell

UICollectionView Flow Layout Inner Constraints

我有一个UICollectionView,它使用xib中定义的流布局和动态宽度单元格。 xib对包含动态标签和静态图像的堆栈视图的所有边都有约束。这些约束应根据configureCell(cellData:, padding:)中提供的边距进行更改,该边距在cellForItemAtsizeForItemAtIndexPath数据源/委托方法上调用。不幸的是,如果我将约束更改为systemLayoutSizeFitting()中的其他内容,则configureCell(cellData:, padding:)返回的尺寸不正确。

UICollectionViewCell xib subclass

我已经在我能想到的每一个组合中尝试过setNeedsLayout()layoutIfNeeded()setNeedsUpdateConstraints()updateConstraintsIfNeeded()。我也试过these solutions但没有成功。

如何更新UICollectionViewCell中的约束并在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子类:

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
    }
}

1 个答案:

答案 0 :(得分:0)

问题结果是操作员错误。

我在configureCell(cellData:, padding:)给了一个不同的填充:

collectionView(_ collectionView:, cellForItemAt indexPath:)

比我放弃:

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

导致视图无法正确显示。