![](/img/trans.png)
[英]UICollectionView DidDeselectItemAtIndexPath method not called in Swift
[英]Swift 2 - Fatal Error when `didDeselectItemAtIndexPath` is called
我有一個UICollectionView
,我使用函數didSelectItemAtIndexPath
來選擇一個單元格並更改其alpha。
在UICollectionView
有12個單元格。
為了將取消選擇的單元格恢復為alpha = 1.0
我使用函數didDeselectItemAtIndexPath
。
到目前為止,代碼工作正常,當我選擇一個單元格並滾動UICollectionView
,應用程序崩潰就行了let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
在deselect函數里面有錯誤:
致命錯誤:在展開可選值(lldb)時意外發現nil
我想我需要重新加載集合視圖但是如何重新加載並保持選中單元格?
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
colorCell.alpha = 0.4
}
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
colorCell.alpha = 1.0
}
發生崩潰是因為您選擇並滾動出屏幕可見區域的單元格已被重用於集合視圖中的其他單元格。 現在,當您嘗試使用cellForItemAtIndexPath
在didDeselectItemAtIndexPath
獲取所選單元格時,會導致崩潰。
為避免崩潰,如@Michael Dautermann所述,使用可選綁定來驗證單元格是否為零然后設置alpha
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
cell.alpha = 1.0
}
}
為了在滾動期間保持選擇狀態,請檢查單元格的選擇狀態,並在cellForItemAtIndexPath
方法cellForItemAtIndexPath
單元格出列時相應地設置alpha
值
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
if cell.selected {
cell.alpha = 0.4
}
else {
cell.alpha = 1.0
}
return cell
}
cellForItemAtIndexPath
似乎返回一個可選項,為什么不這樣做:
override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
if let colorCell = collectionView.cellForItemAtIndexPath(indexPath) {
colorCell.alpha = 1.0
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.