【问题标题】:collectionViewLayout.collectionViewContentSize getting SIGABRTcollectionViewLayout.collectionViewContentSize 获取 SIGABRT
【发布时间】:2023-03-05 08:22:01
【问题描述】:

我尝试按照这个解决方案 (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。

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

【问题讨论】:

    标签: swift uicollectionview uicollectionviewlayout


    【解决方案1】:

    您可能会得到无限递归,因为为了知道集合视图的内容大小,它需要知道每个项目的大小。集合视图调用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)
    }
    

    【讨论】:

    • 您的答案有效,但随后又导致了另一个问题。我在 collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) 中调用 flowLayout.itemSize.width,它现在返回错误的大小.. ?
    • 你真的应该避免基于其他布局尺寸的布局尺寸。
    • 一旦我设置了尺寸,在另一个回调中我应该根据什么来设置尺寸和间距?
    • 这取决于您的需求。我的回答假设您希望单元格大小基于集合视图本身的可见大小。
    • 我想根据屏幕上的集合视图大小来确定单元格大小。我想将单元格的间距基于单元格的大小,所以我想我不确定 flowLayout.itemSize 和 flowLayout.minimumInteritemSpacing 对应于什么
    猜你喜欢
    • 1970-01-01
    • 2012-03-21
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多