简体   繁体   中英

UICollectionView didDeselectItemAtIndexPath effects multiple cells and gives "nil"

I have an horizontal collection view containing 11 cells when selecting a cell its border changes to green. The problem I have is that when I select the cells it changes the border of the not visible cells.

Also when I select the last cells the app crashes giving "fatal error: unexpectedly found nil while unwrapping an Optional value" referring to didDeselectItemAtIndexPath .

What could be the problem?

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
        }

    }

}

change your function to do some if-let optional checking:

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

More information can be seen in this related question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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