为什么我的自定义 UICollectionViewLayout 在单元格之间添加空格时会抛出错误? [英] Why does my custom UICollectionViewLayout throw an error when adding space between cells?
问题描述
我正在制作一个用于练习的自定义 UICollectionViewLayout
类,主要是试图重现单元格无限水平布置的水平流布局.
I'm making a custom UICollectionViewLayout
class for practice, essentially trying to reproduce the horizontal flow layout where cells are laid out horizontally infinitely.
一切都与我的 prepare()
和 layoutAttributesForElements()
函数完美配合,如下所示:
Everything was working perfectly with my prepare()
and layoutAttributesForElements()
functions looking like this:
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()
中的下一行的 x 坐标中添加一组值 spacing
时出现问题,以便集合视图中的第一个单元格有一个向左的插图:
The problem arises when I try to add an inset of value spacing
to the x coordinate in following line in prepare()
so that the first cell in the collection view has a leftwards inset:
frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)
一旦我这样做,一切看起来都很好,直到我尝试在集合视图中滑动.抛出以下异常:
As soon as I do, everything looks well and good until I try swiping through the collection view. The following exception is thrown:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0x618000036060> {length = 2, path = 0 - 3}'
有人能解释一下为什么会这样吗?有没有其他方法可以实现布局?
Would someone please explain why this is happening? Is there an alternative way of achieving the layout?
推荐答案
找到解决方案!显然覆盖 layoutAttributesForItem(at indexPath: IndexPath) ->UICollectionViewLayoutAttributes?
解决了这个问题!但我不知道为什么.
Found the solution! Apparently overriding layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?
fixes the issue! But I have no idea why.
这篇关于为什么我的自定义 UICollectionViewLayout 在单元格之间添加空格时会抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!