如何使 UICollectionViewCell 宽度自动调整大小且其高度保持不变

How to make UICollectionViewCell's width auto resize and its height stay the same

我希望我的自定义 UICollectionViewCellwidth 根据内部的 UILabel 内容动态变化,但每个单元格应保持相同的高度。使用 estimatedItemSize 也会更改 height 值(这不是我想要的,我需要它保持不变,比如 30。) 重新加载数据几次后开始变得混乱,使某些单元格无法垂直对齐。

您是否尝试实施

collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize

最后我通过在 sizeForItemAtIndexPath 中使用 sizeWithAttributes 动态确定每个单元格的宽度来解决这个问题。