Swift 2 - 调用“didDeselectItemAtIndexPath”时出现致命错误

Swift 2 - Fatal Error when `didDeselectItemAtIndexPath` is called

我有一个 UICollectionView,我在其中使用函数 didSelectItemAtIndexPath 到 select 一个单元格并更改其 alpha。

UICollectionView 中有 12 个单元格。

为了将删除的select单元格恢复到alpha = 1.0,我使用函数didDeselectItemAtIndexPath

到目前为止,代码仍然有效,当我 select 一个单元格并滚动 UICollectionView 时,应用程序在 deselect 函数内的 let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)! 行崩溃错误:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

我想我需要重新加载集合视图,但如何重新加载并保持单元格 selected?

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
    }
}

发生崩溃是因为您选择并滚出屏幕可见区域的单元格已被集合视图中的其他单元格重复使用。现在,当您尝试使用 cellForItemAtIndexPathdidDeselectItemAtIndexPath 中获取选定的单元格时,它会导致崩溃。

如@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
}