Reputation: 129
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
}
}
Upvotes: 0
Views: 353
Reputation: 5823
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.
Upvotes: 1
Reputation: 297
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!!
Upvotes: 0