在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/C++  iOS/ Swift: CollectionView的didDeselectItemAt

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

開(kāi)發(fā)語(yǔ)言: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ì)出問(wèn)題

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

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

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

類(lèi)型強(qiáng)應(yīng)該是這么寫(xiě)

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

不過(guò)didSelectItemAt返回的是UICollectionViewCell?可選類(lèi)型, 建議你加上guard對(duì)其解包.

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