-1

so I am trying to change the background color of the collection view cell that is clicked, however, when I call the CollectionView.reloadData() method the backgrounds don't change. I am thinking that reloading the data only checks for adding and deleting cells, but does not actually call the configure function for each cell again. I was wondering how I can reconfigure these cells so that the background color can change for the selected cell. Thanks for the help in advance!

This is the method that I call:

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

    ...

    bagCollectionView.reloadData()
}
  • Provide the code sample for changing color. – ajith Kumark Aug 10 '20 at 04:36
  • Instead of using reloadData(), you can use collectionView 'didSelectItemAt' and 'didDeSelectItemAt' delegates to manage this – ajith Kumark Aug 10 '20 at 04:39
  • 1
    You have to store index somewhere, store selected item index and then reload collection, After that implement the logic for show different color for selected row in cell for item. For example, cell.backgroundcolor = selectedIndex == indexPath.item ? .red : .yellow. – Bhavin Vaghela Aug 10 '20 at 04:43

2 Answers2

1

Instead of calling reloadData, you can try:

 override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.backgroundColor = yourColor
    }
Amr
  • 286
  • 1
  • 2
  • 10
1

Even though you do your logic in did select by finding a cell or implement logic in didSelectItemAt and didDeSelectItemAt, I suggest you should store the Index. Due to reusability of cell, there is chance that selected cell do not show color on scroll or if you have large number or records.

So save index in array(for multiple selections) or a single variable(single selection) and manage logic for the same.

For example:

cell.backgroundColor = selectedIndex == indexPath.item ? .red : .yellow 
Bhavin Vaghela
  • 654
  • 1
  • 5
  • 19