2017-01-13 76 views
0

当我在模拟器上运行它工作正常。但是,当我在物理设备上运行,我遇到一个错误 - index out of range
代码:scrollToItem UICollectionView错误 - 索引超出范围

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滚动到顶部,当我点击。

+0

错误发生,为什么你尝试做什么? – Honey

+0

我收到类似的问题。你能解决这个问题吗?你如何能够确定问题将在何处形成? – user805981

回答

1

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

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

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

+0

但错误停留。只有设备,在模拟器上ok –

+0

你的代码在哪里得到错误?它在您发布的问题中的代码中吗? – nathan

0

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