2017-10-11 43 views
0

每次我嘗試選擇一個單元格是不可見的時候,我得到一個異常:斯威夫特3 - 的CollectionView選擇不可見

let cell = collectionView.cellForItem(at: indexPath) as! CustomCell 

這就是爲什麼我決定先滾動到它,所以它得到分享範圍,然後選擇它:

collectionView.scrollToItem(at: indexPath, at: [], animated: true) 
let cell = collectionView.cellForItem(at: indexPath) as! CustomCell 

但我仍然得到:

fatal error: unexpectedly found nil while unwrapping an Optional value 

這一行:

let cell = collectionView.cellForItem(at: indexPath) as! CustomCell 

有人可以幫我解決這個問題嗎?

感謝和問候!

+1

由於'cellForItem'定義爲不可見的單元格返回nil,所以我必須問,爲什麼要嘗試選擇一個呢? (我懷疑滾動的問題是,直到事件循環運行才更新用戶界面,因此單元格沒有機會變得可見......但我不確定這一點。) –

+0

爲什麼你想要選擇一個不可見的單元格? –

+0

我正在執行預選,並且必須預選的單元格不可見...所以? –

回答

0

我們已經在UICollectionViewDelegate中做了select方法。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 
     //here you can access the cell 
     guard let cell = collectionView.cellForItem(at: indexPath) as? 
     CustomCell else { return } 
     //write your code here 
}