scrollToItem UICollectionView错误 - 索引超出范围

时间:2017-01-13 18:49:32

标签: ios swift xcode

当我在模拟器上运行时,它可以正常工作。但是当我在物理设备上运行时,我遇到了错误 - index out of range
代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let index = NSIndexPath(row: 0, section: 0) as IndexPath
    resultController?.collectionView?.scrollToItem(at: index, at: .bottom, animated: true)
}

截图: enter image description here

P.S:点击时,我希望UICollectionView滚动到顶部。

2 个答案:

答案 0 :(得分:1)

要滚动到视图顶部,请使用setContentOffset方法。

collectionView?.setContentOffset(CGPoint.zero, animated: true)

您的问题是由集合视图的自动单元重用引起的,它会在单元格离开屏幕时使单元格出列。这有时会导致第一个索引处没有单元格,这就是索引超出范围错误的原因。

答案 1 :(得分:0)

我已在我的项目中测试了您的代码。它工作正常。请检查您的resultController?.collectionView?是否正确。