2017-01-13 75 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?是否正確。