【问题标题】:Swift 2 - Fatal Error when `didDeselectItemAtIndexPath` is calledSwift 2 - 调用“didDeselectItemAtIndexPath”时出现致命错误
【发布时间】:2015-11-27 17:10:08
【问题描述】:

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

UICollectionView 中有 12 个单元格。

为了将取消选择的单元格带回alpha = 1.0,我使用函数didDeselectItemAtIndexPath。

到目前为止,代码仍然有效,当我选择一个单元格并滚动 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
    }

【问题讨论】:

    标签: ios uicollectionview swift2 fatal-error didselectrowatindexpath


    【解决方案1】:

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

    如@Michael Dautermann 所述,为避免崩溃,请使用可选绑定来验证单元格是否为零,然后设置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
    }
    

    【讨论】:

    • 非常感谢您的解释.. 非常清晰且有效
    【解决方案2】:

    cellForItemAtIndexPath 似乎返回了一个可选的,所以为什么不这样做:

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

    【讨论】:

      猜你喜欢
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 2017-06-07
      • 1970-01-01
      相关资源
      最近更新 更多