我正在制作一个自定义 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/