Swift collectionViewLayout.collectionViewContentSize获取SIGABRT

Swift collectionViewLayout.collectionViewContentSize获取SIGABRT,swift,uicollectionview,uicollectionviewlayout,Swift,Uicollectionview,Uicollectionviewlayout,我尝试按照此解决方案()确定UICollectionViewLayout的大小,以便相应地调整单元格的大小。下面的代码调用collectionViewContentSize,调用时会抛出错误: func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CG

我尝试按照此解决方案()确定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)
}
func collectionView(collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:indexPath)->CGSize{
设frameWidth=collectionViewLayout.collectionViewContentSize.width
设maxCellWidth=(frameWidth)/(7.0/6.0+6.0)
设frameHeight=collectionViewLayout.collectionViewContentSize.height
设maxCellHeight=frameHeight
设cellEdge=maxCellWidth
错误是线程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)
}
func collectionView(collectionView:UICollectionView,布局collectionViewLayout:UICollectionViewLayout,sizeForItemAt indexPath:indexPath)->CGSize{
设frameWidth=collectionView.frame.width
设maxCellWidth=(frameWidth)/(7.0/6.0+6.0)
设frameHeight=collectionView.frame.height
设maxCellHeight=frameHeight
设cellEdge=maxCellWidth
你的答案是有效的,但它会导致另一个问题。我在collectionView中调用flowLayout.itemSize.width(collectionView:UICollectionView,layout collectionViewLayout:UICollectionViewLayout,InsettForSection at section:Int),它现在返回错误的大小?您确实应该避免将布局大小基于其他布局大小。一旦我设置了大小,我应该在另一个回调中基于什么大小和间距?这取决于您的需要。我的回答假设您希望单元格大小基于集合视图本身的可见大小。我希望单元格大小基于屏幕上集合视图的大小。我想根据单元格的大小来确定单元格的间距,所以我想我不确定flowLayout.itemSize和flowLayout.minimumItemSpacing对应的是什么