Why didDeselectItemAt from UICollectionView throw an unexpected nil error and Swift application crashes?

I used the collection view to display a collection of images. It works, but when I use the function didDeselectItemAt, it will work if I click on certain images.

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

Code setup:

numberOfItemsInSection:

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

cellForItemAt:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellIdentifier = "ImageCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! ImageCollectionViewCell

        let imageUrls = collection?.imageUrls

        // Configure the cell
        // Reset alpha of first item in collection
        if indexPath.row == 0 {
            cell.imageView.alpha = 1.0

            if videoUrl != nil {
                cell.backgroundColor = UIColor.red
                cell.imageView.alpha = 0.5
            }
        }
        cell.imageView.af_setImage(withURL: URL(string: (imageUrls?[indexPath.row])!)!)

        return cell
    }

didDeselectItemAt:

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell

        UIView.animate(withDuration: 0.3, animations: {
            cell.imageView.alpha = 0.6
        })
    }

didSelectItemAt:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("You've tapped me. NICE!! \(indexPath.row)")

        let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell

        cell.imageView.alpha = 1

        let url = self.collection?.imageUrls?[indexPath.row]
        self.selectedImageUrl = url

        Alamofire.request(url!).responseImage(completionHandler: {
            (response) in
            if response.result.value != nil {
                self.selectedImage.image = response.result.value
            }
        })

    }

The above code works, but will cause an error if I click on certain images. The first cell of each type of collection has an alpha of 100% - 1.0, and all the others have an alpha of 0.6. I noticed that - in addition to the first cell in the collection - every 7th cell also has an alpha of 100%, and if there is a video interface in the collection view, it will have a red background and an alpha of 50%.

- , UITableViewController, dequeueReusableCell, didDeselectItemAt - ?

, 100, 60%. videoUrl, 50% .

, , . !

UPDATE:

, , . ,

print("OUTPUT \(String(describing: collectionView.cellForItem(at: indexPath)))")

, didSelectItemAt, didDeselectItemAt:

didSelectItemAt:

OUTPUT Optional(<CollectionViewApp.ImageCollectionViewCell: 0x7ff61679c1a0; baseClass = UICollectionViewCell; frame = (150 0; 150 100); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x6080000347c0>>)

didDeselectItemAt:

OUTPUT ( > )

, , . :

OUTPUT Optional(<CollectionViewApp.ImageCollectionViewCell: 0x7fc3cb038540; baseClass = UICollectionViewCell; frame = (150 0; 150 100); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x610000225980>>)

, , : OUTPUT Optional(<CollectionViewApp.ImageCollectionViewCell: 0x7fc3cb03afb0; baseClass = UICollectionViewCell; frame = (300 0; 150 100); clipsToBounds = YES; opaque = NO; layer = <CALayer: 0x6100002264c0>>).

, , , . .

+4
1

, , didDeselectItemAt , . UICollectionView UICollectionViewCells, , collectionView.cellForItem(at: indexPath) , . , :

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    guard let cell = collectionView.cellForItem(at: indexPath) as! ImageCollectionViewCell else {
        return //the cell is not visible
    }

    UIView.animate(withDuration: 0.3, animations: {
        cell.imageView.alpha = 0.6
    })
}

:

, .

:

guard let url = self.collection?.imageUrls?[indexPath.row] else {
    fatalError("url was nil")
}

self.selectedImageUrl = url

Alamofire.request(url).responseImage(completionHandler: {
    (response) in
    if response.result.value != nil {
        self.selectedImage.image = response.result.value
    }
})

, , . .

, - :

let cellIdentifier = "ImageCell"
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? ImageCollectionViewCell else  {
    fatalError("Wrong cell type")
}

,

+4

Source: https://habr.com/ru/post/1662681/


All Articles