鍍金池/ 問答/C++  iOS/ Swift: CollectionView的didDeselectItemAt

Swift: CollectionView的didDeselectItemAt indexPath:方法報(bào)錯(cuò)

開發(fā)語言:Swift3.2
使用CollectionView的代理方法:didSelectItemAt,報(bào)錯(cuò)行代碼如下

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

錯(cuò)誤信息:fatal error: unexpectedly found nil while unwrapping an Optional value

具體引起報(bào)錯(cuò)的操作為先選中一個(gè)cell,再將這個(gè)cell滑出屏幕外,再點(diǎn)擊任意一個(gè)cell,程序就會(huì)崩潰.

相同代碼使用OC就不會(huì)報(bào)錯(cuò),用Swift3.2會(huì)出問題

回答
編輯回答
舊時(shí)光

對Optional類型強(qiáng)制解包的前提是你得知道其值一定不為nil,否則需要判斷

if let cell =  collectionView.cellForItem(at: indexPath) as? ChargeUpCollectionViewCell {
 // cell可以操作了
}
2017年4月24日 05:30
編輯回答
刮刮樂

類型強(qiáng)應(yīng)該是這么寫

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

不過didSelectItemAt返回的是UICollectionViewCell?可選類型, 建議你加上guard對其解包.

guard let cell = collectionView.cellForItem(at: indexPath) else {
    return
}
2017年7月2日 17:43