簡體   English   中英

Swift 2 - 調用`didDeselectItemAtIndexPath`時出現致命錯誤

[英]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
    }

發生崩潰是因為您選擇並滾動出屏幕可見區域的單元格已被重用於集合視圖中的其他單元格。 現在,當您嘗試使用cellForItemAtIndexPathdidDeselectItemAtIndexPath獲取所選單元格時,會導致崩潰。

為避免崩潰,如@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM