swift - 为什么我的自定义 UICollectionViewLayout 在单元格之间添加空间时会抛出错误?

标签 swift uicollectionviewlayout

我正在制作一个自定义 UICollectionViewLayout 类进行练习,本质上是尝试重现单元格无限水平布局的水平流布局。

一切都与我的 prepare()layoutAttributesForElements() 函数完美配合,如下所示:

override func prepare() {
    cache.removeAll(keepingCapacity: false)

    var frame = CGRect.zero

    for item in 0..<numberOfItems {
        let indexPath = IndexPath(item: item, section: 0)
        let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)
        attributes.frame = frame
        cache.append(attributes)
    }
}

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    var layoutAttributes = [UICollectionViewLayoutAttributes]()
    for attributes in cache {
        if attributes.frame.intersects(rect) {
            layoutAttributes.append(attributes)
        }
    }
    return layoutAttributes
}

当我尝试在 prepare() 中的下一行中将值 spacing 的插入添加到 x 坐标时,就会出现问题,以便 Collection View 中的第一个单元格有一个向左插入:

frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)

一旦我这样做,一切看起来都很好,直到我尝试滑动 Collection View 。抛出以下异常:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0x618000036060> {length = 2, path = 0 - 3}'

有人可以解释一下为什么会发生这种情况吗?是否有其他方法来实现布局?

最佳答案

找到解决方案了!显然重写 layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? 解决了这个问题!但我不知道为什么。

关于swift - 为什么我的自定义 UICollectionViewLayout 在单元格之间添加空间时会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40118330/

相关文章:

ios - 如何在出现 TouchID 警报时删除状态栏?

swift - 更改场景中的 SKS 文件

iOS:即使单元格可见,cellForItemAtIndexPath 也返回 nil

ios - swift 。使用 IBOutlet 更改多个 UIButton

swift - 以编程方式退出终端 Mac 应用程序?

ios - 如何在 Swift 中隐藏 UITableView?

ios - 动态设置 UICollectionViewCell 的大小

ios - 如何在 iOS7 上的 UICollectionView 中制作粘性标题?

ios - 根据框架大小自动调整 UICollectionViewCell 中的单元格大小

ios - 将第一个和最后一个 UICollectionViewCell 的位置设置在 UICollectionView 的中心