Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
leaner122 Avatar asked Sep 20 '16 07:09

leaner122


1 Answers

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

    }
like image 99
Moriya Avatar answered Nov 05 '22 23:11

Moriya