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

Why does my custom UICollectionViewLayout throw an error when adding space between cells?

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

我的 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
}

当我尝试将值 spacing 的插图添加到 prepare() 的下一行中的 x 坐标时,出现了问题,以便集合视图中的第一个单元格具有向左的插图:

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

只要我这样做,一切看起来都很好,直到我尝试在集合视图中滑动。抛出以下异常:

*** 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? 解决了这个问题!但是我不知道为什么。