UICollectionView 单元格忽略 UICollectionViewDelegateFlowLayout - sizeForItemAt

UICollectionView cell ignores UICollectionViewDelegateFlowLayout - sizeForItemAt

我正在尝试布局 collectionViewCell 的大小,以便在每一行中有 7 个单元格(简单吧?)。

单元格很简单,只有一个UILabel,上下左右约束均为0。

我已经设置了如下的 sizeForItemAt 方法,确保我的控制器是一个 collectionViewDelegateFlowLayout、collectionViewDelegate 和 collectionViewDataSource,并且 collectionview.delegate 和 .datasource = self。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let safeScreenWidth = self.view.frame.size.width - 30

        let width: CGFloat = (safeScreenWidth / 7)
        let height: CGFloat = 40.0

        return CGSize(width: width, height: height)
    }

该方法被正确调用(使用断点和 print() 检查)但是单元格决定完全忽略给定的大小并以刚好足以包含其标签文本的大小出现(如果标签文本为空应用程序崩溃 "Invalid parameter not satisfying: !CGSizeEqualToSize(size, CGSizeZero)").

我试过设置不同的尺寸,例如 width = 200, height = 200;但没有任何变化单元格总是很小,正如我所说,刚好适合其标签的文本。

一个快速解决方法是在 cellForItemAt 中为标签设置高度和宽度限制,但我想了解为什么 sizeForItemAt 不起作用。

出于某种原因,自动估计的大小比 sizeForItemAt 方法计算的优先级更高。

尝试将 collectionViews 估计大小设置为 None