简体   繁体   English

展开可选值时,UiCollectionView单元意外发现为零

[英]UiCollectionView Cell unexpectedly found nil when unwrapping optional value

In this function I'm calling didSelectItemAtIndexPath to notify the collection view that I want certain cells selected: 在此函数中,我调用didSelectItemAtIndexPath来通知集合视图我希望选择某些单元格:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

//some code here
....
//cell!.contentView.addSubview(pulseView)
        if (strings_chosen[indexPath.row] as! Bool) {
            self.collectionView(self.collectionView!, didSelectItemAtIndexPath: indexPath)
            cell!.backgroundColor = MaterialColor.grey.lighten1;
        } else {
            cell!.backgroundColor = MaterialColor.white
            self.collectionView(self.collectionView!, didDeselectItemAtIndexPath: indexPath)
        }
...
}

However I'm getting nil here (for cell ). 但是我在这里得到nil (对于cell )。 Specifically the error is fatal error: unexpectedly found nil while unwrapping an Optional value : 具体来说,该错误是fatal error: unexpectedly found nil while unwrapping an Optional value

override func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    let cell:UICollectionViewCell? = collectionView.cellForItemAtIndexPath(indexPath)
    cell!.selected = false; //THIS LINE IS GIVING ME AN ERROR
    strings_chosen[indexPath.row] = false;
    cell!.backgroundColor = MaterialColor.white
    updateDeleteButtonTitle()
}

I don't understand why cell is nil, I'm pretty sure I'm grabbing the cell at the correct indexPath. 我不明白为什么cell为零,我很确定我正在正确的indexPath处抓取单元格。 Any reason why cell could be nil? 细胞为何为零的任何原因?

当该单元格在屏幕上不可见时, cellForItemAtIndexPath返回nil

It will be calling cellForItemAtIndexPath inside of didDeselectItemAtIndexPath before the cell is returned inside of cellForItemAtIndexPath, so the cell is nil. 在单元格返回到cellForItemAtIndexPath内部之前,它将在didDeselectItemAtIndexPath内部调用cellForItemAtIndexPath,因此该单元格为nil。

Instead of calling the functions directly try calling selectItemAtIndexPath and deselectItemAtIndexPath. 与其直接调用函数,不如尝试调用selectItemAtIndexPath和deselectItemAtIndexPath。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM