这是我目前在自定义CollectionView布局中的代码
/* Returns the item index of the currently middle cell */
var middleItemIndex: Int {
get {
let centerPoint = CGPoint(x: collectionView!.center.x + collectionView!.contentOffset.x,
y: collectionView!.center.y + collectionView!.contentOffset.y)
let centerCellIndexPath = collectionView?.indexPathForItemAtPoint(centerPoint)
return (centerCellIndexPath?.item)!
}
}
override func prepareLayout() {
print(middleItemIndex)
}
我在exc_bad_access
的行上一直收到indexPathForItemAtPoint
错误。在进一步检查时,我的堆栈跟踪显示它不断重复collectionview的prepareForLayout()
和上面的featuredItemIndex
方法,这使我相信featuresItemIndex中的代码包含无限循环,最终会产生堆栈溢出。
我无法看到导致错误的原因。在自定义布局类中调用collectionview的属性是否会创建无限循环?如果是这样的话,有没有办法在集合视图中找到中间单元格的索引?我的集合视图看起来就像一个tableview,我正在使用collectionview,因为会有很多与单元格布局的自定义交互
答案 0 :(得分:0)
我认为使用indexPathsForVisibleItems
来查找中间索引会更好。我不确定indexPathForItemAtPoint
的机制。也许它将重新布置细胞以测试你的位置是否在你的细胞中。但实际上,您可以使用indexPathsForVisibleItems
来使中间索引路径更容易,更安全。