Ios Swift 2-调用'DidDecelectItemAtIndexPath'时发生致命错误

Ios Swift 2-调用'DidDecelectItemAtIndexPath'时发生致命错误,ios,uicollectionview,swift2,fatal-error,didselectrowatindexpath,Ios,Uicollectionview,Swift2,Fatal Error,Didselectrowatindexpath,我有一个UICollectionView,其中我使用函数didSelectItemAtIndexPath选择一个单元格并更改其alpha值 在UICollectionView中有12个单元格 为了将取消选择的单元格恢复到alpha=1.0我使用函数diddesceleitematindexpath 然而,到目前为止,代码仍然有效,当我选择一个单元格并滚动UICollectionView时,应用程序会在let colorCell:UICollectionViewCell=collectionVie

我有一个
UICollectionView
,其中我使用函数
didSelectItemAtIndexPath
选择一个单元格并更改其alpha值

UICollectionView
中有12个单元格

为了将取消选择的单元格恢复到
alpha=1.0
我使用函数
diddesceleitematindexpath

然而,到目前为止,代码仍然有效,当我选择一个单元格并滚动
UICollectionView
时,应用程序会在
let colorCell:UICollectionViewCell=collectionView.cellForItemAtIndexPath(indexPath)在“取消选择”功能内,出现错误:

致命错误:在展开可选值时意外发现nil (lldb)

我想我需要重新加载集合视图,但如何重新加载并保持单元格处于选中状态

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
似乎返回了一个可选的,那么为什么不:

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    if let colorCell = collectionView.cellForItemAtIndexPath(indexPath) {
       colorCell.alpha = 1.0
    }
}

发生崩溃的原因是您选择并从屏幕可见区域中滚动出来的单元格已被集合视图中的其他单元格重新使用。现在,当您尝试使用
cellForItemAtIndexPath
didecelitematindexpath
中获取所选单元格时,它导致崩溃

如@Michael Dautermann所述,为了避免崩溃,请使用可选绑定验证单元格是否为nil,然后设置
alpha

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
        cell.alpha = 1.0
    }
}
为了在滚动过程中保持选择状态,请检查单元格的选择状态,并在
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
}

非常感谢你的解释。。非常清楚,它的工作