ios - Swift 2 - 调用 `didDeselectItemAtIndexPath` 时出现 fatal error

标签 ios uicollectionview swift2 fatal-error didselectrowatindexpath

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

UICollectionView有12个单元格。

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

到目前为止,当我选择一个单元格并滚动 UICollectionView 时,代码可以正常工作。应用程序上线时崩溃let colorCell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!在取消选择函数内出现错误:

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

我想我需要重新加载 Collection View ,但是如何重新加载并保持单元格处于选中状态?

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
    }

最佳答案

发生崩溃的原因是您选择并滚动到屏幕可见区域之外的单元格已被 Collection View 中的其他单元格重复使用。现在,当您尝试使用 cellForItemAtIndexPath 获取 didDeselectItemAtIndexPath 中选定的单元格时,会导致崩溃。

为了避免崩溃,正如 @Michael Dautermann 提到的,使用可选绑定(bind)来验证单元格是否为零,然后设置 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
}

关于ios - Swift 2 - 调用 `didDeselectItemAtIndexPath` 时出现 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33962068/

相关文章:

ios - 使用 ARC 的安全框架内存泄漏

ios - 如何在某个位置通知附近的用户

ios - 如何更改 UICollectionView 中的滚动方向?

ios - 如何在 Swift 中解析具有多个数组的 JSON

ios - 如何在 BarCharts IOS 图表中创建多个数据集

ios - 用于捕获 iPhone 流量的 Charles 在 iOS8 上不起作用

ios - 为什么我的标签在从 UITextField 更新 UILabel 时留下了 1 个字符?

swift - 如何向多个 UIViewControllers 添加点击手势

像 iOS collectionView 一样具有多列的 android 表

swift - 核心数据 [NSSet intersectsSet :]: set argument is not an NSSet