UICollectionView didDeselectItemAtIndexPath影响多个单元格并给出" nil"

时间:2016-04-03 20:13:54

标签: ios swift uicollectionviewcell

我有一个包含11个单元格的水平集合视图,当选择一个单元格时,它的边框变为绿色。我遇到的问题是,当我选择单元格时,它会更改不可见单元格的边框。

此外,当我选择最后一个单元格时,应用程序崩溃,给出了#34;致命错误:在展开“可选”值时意外发现nil"提到didDeselectItemAtIndexPath

可能是什么问题?

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return frameArray.count
    }

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

        let frameCell = collectionView.dequeueReusableCellWithReuseIdentifier("frameCell", forIndexPath: indexPath) as! FrameViewCell

        dispatch_async(dispatch_get_main_queue()) {
            frameCell.imageView.image = UIImage(named: self.frameArray[indexPath.row])
        }

        return frameCell
    }

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

        dispatch_async(dispatch_get_main_queue()) {
            let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as! FrameViewCell

            frameCell.layer.borderWidth = 2
            frameCell.layer.borderColor = UIColor.greenColor().CGColor
            frameCell.imageView.alpha = 1.0

            self.globalFrameIndex = self.frameArray[indexPath.row]
            self.framesImageViews(self.globalFrameIndex, image: self.globalImage)


            print(self.frameArray[indexPath.row])
        }
    }

    func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {

        dispatch_async(dispatch_get_main_queue()) {
            let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as! FrameViewCell

            frameCell.layer.borderWidth = 1
            frameCell.layer.borderColor = UIColor.whiteColor().CGColor
            frameCell.imageView.alpha = 0.5
        }

    }

}

1 个答案:

答案 0 :(得分:0)

更改您的函数以执行一些if-let可选检查:

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {

    dispatch_async(dispatch_get_main_queue()) {
        if let frameCell = collectionView.cellForItemAtIndexPath(indexPath) as? FrameViewCell
        {
            frameCell.layer.borderWidth = 1
            frameCell.layer.borderColor = UIColor.whiteColor().CGColor
            frameCell.imageView.alpha = 0.5
        } 
    }
}

可以看到更多信息in this related question

相关问题