【发布时间】:2016-10-18 21:24:34
【问题描述】:
我正在制作一个自定义的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
}
当我尝试将值 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}'
有人能解释一下为什么会这样吗?有没有其他实现布局的方法?
【问题讨论】:
标签: swift uicollectionviewlayout