修改底层布局约束时 UICollectionViewCell 子类大小不正确
Posted
技术标签:
【中文标题】修改底层布局约束时 UICollectionViewCell 子类大小不正确【英文标题】:UICollectionViewCell subclass incorrect size when modifying underlying layout constraints 【发布时间】:2017-05-26 00:39:34 【问题描述】:我有一个UICollectionView
,它使用在 xib 中定义的流布局和动态宽度单元格。 xib 在包含动态标签和静态图像的堆栈视图的所有方面都有约束。这些约束应根据configureCell(cellData:, padding:)
中提供的边距进行更改,该边距在cellForItemAt
和sizeForItemAtIndexPath
数据源/委托方法上调用。不幸的是,如果我将约束更改为 configureCell(cellData:, padding:)
中的其他内容,systemLayoutSizeFitting()
返回的大小不正确。
我已经尝试了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】:问题原来是操作员错误。
我给 configureCell(cellData:, padding:)
一个不同的填充:
collectionView(_ collectionView:, cellForItemAt indexPath:)
比我付出的:
collectionView(collectionView:, layout collectionViewLayout:, sizeForItemAtIndexPath indexPath:)
这导致视图无法正确显示。
【讨论】:
以上是关于修改底层布局约束时 UICollectionViewCell 子类大小不正确的主要内容,如果未能解决你的问题,请参考以下文章
ios xib和代码的frame布局 iOSXib布局后代码修改约束的值