UICollectionView selected cells issue

2019-06-12 10:45发布

问题:

I have UICollectionView, i am selected cell with didSelectItemAt and deselect with didDeselectItemAt but selected cells are replaced

https://im4.ezgif.com/tmp/ezgif-4-2715e62591.gif

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

       let cell = collectionView.cellForItem(at: indexPath)

       // print(indexPath)

        let collectionActive: UIImageView = {
            let image=UIImageView(image: #imageLiteral(resourceName: "collectionActive"))
            image.contentMode = .scaleAspectFill
            return image
        }()




        if cell?.isSelected == true {
            cell?.backgroundView = collectionActive
        }

    }

    func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
        return true
    }

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

        let collectionInactive: UIImageView = {
            let image=UIImageView(image: #imageLiteral(resourceName: "collectionInactive"))
            image.contentMode = .scaleAspectFill
            return image
        }()


        if cell?.isSelected == false {
            cell?.backgroundView = collectionInactive
        }

    }

回答1:

I have also worked on same things, I have following solution for that.

You need to create array of indexPath which will store selected indexPath.

var arrSelectedIndexPath = [IndexPath]()

In cellForRowAtItem method add following code which will check if arrSelectedIndexPath contains indexPath then display selected active background else display inactive background.

if arrSelectedIndexPath.contains(indexPath) {
    cell?.backgroundView = collectionActive
} else {
    cell?.backgroundView = collectionInactive
}

In didSelect method you need to add following code which also same as above logic, but just add or remove indexPath.

if arrSelectedIndexPath.contains(indexPath) {
    cell?.backgroundView = collectionInactive
    arrSelectedIndexPath.remove(at: arrSelectedIndexPath.index(of: indexPath)!)
} else {
    cell?.backgroundView = collectionInactive
    arrSelectedIndexPath.append(indexPath)
}

I hope this solution work for you.



回答2:

Try the following code. In "didSelectItemAt" function add converse condition also:

if cell?.isSelected == true {
        cell?.backgroundView = collectionActive
} else {
       cell?.backgroundView = collectionInactive
}

Similarly, in "didDeselectItemAt" add this condition:

if cell?.isSelected == false {
        cell?.backgroundView = collectionInactive
} else {
        cell?.backgroundView = collectionActive
}

This problem occurs whenever we are reusing the cells. Above code might help you!!