leaner122 leaner122 - 2 months ago 29
Swift Question

Deselect a collectionview cell when another cell is selected

I have cells with images on a

viewController
, I like to give the users an option to select one of the
image
for their
title label
. How do I make them select only one
image
, that is if they select another
image
I want to deselect the previous
image
they selected.

This is what I did:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 5.0
cell?.layer.borderColor = UIColor.black.cgColor
collectionView.allowsMultipleSelection = false
}


but it is allowing me to select all cells not just one cell which I like.

Answer

First, move collectionView.allowsMultipleSelection = false to viewDidLoad

Secondly, I don't think you really have a problem with multiple selection. Rather that you don't clear the effects you put on the cell when selecting it. What you can do is to clear that i didDeselect

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderWidth = 5.0
        cell?.layer.borderColor = UIColor.black.cgColor

    }

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderWidth = 0
        cell?.layer.borderColor = UIColor.white.cgColor

    }