collectionViewLayout.collectionViewContentSize 获取 SIGABRT

collectionViewLayout.collectionViewContentSize getting SIGABRT

我尝试按照此解决方案 (How to determine height of UICollectionView with FlowLayout) 来确定我的 UICollectionViewLayout 的大小,以便相应地调整单元格的大小。我下面的代码调用了 collectionViewContentSize,它在调用时抛出错误:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {


    let frameWidth  = collectionViewLayout.collectionViewContentSize.width
    let maxCellWidth = (frameWidth) / (7.0/6.0 + 6.0)
    let frameHeight  = collectionViewLayout.collectionViewContentSize.height
    let maxCellHeight = frameHeight

    let cellEdge = maxCellWidth < maxCellHeight ? maxCellWidth : maxCellHeight

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

错误是线程 1 SIGABRT。

知道为什么这不起作用吗?

您可能会得到无限递归,因为为了知道集合视图的内容大小,它需要知道每个项目的大小。集合视图调用 sizeForItemAt 的全部原因是确定集合视图的内容大小。

好消息是您没有理由询问集合视图的内容大小。相反,根据集合视图本身的大小而不是其内容大小来确定项目的大小。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let frameWidth  = collectionView.frame.width
    let maxCellWidth = (frameWidth) / (7.0/6.0 + 6.0)
    let frameHeight  = collectionView.frame.height
    let maxCellHeight = frameHeight

    let cellEdge = maxCellWidth < maxCellHeight ? maxCellWidth : maxCellHeight

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