Sath.Dev
Sath.Dev

Reputation: 89

ios UICollectionView cell selecting and deselecting issue

Im using UIcollection view as my tabbar when I scroll collection view horizontally previous selected cell will not deselect when i select new one

this is my code to change colour when i select a cell and deselect a cell

  var selectedIndexPath : IndexPath = []
func collectionView(_ collectionView: UICollectionView, 
didSelectItemAt indexPath: IndexPath) {

   if let cell = collectionView.cellForItem(at: indexPath) as? 
   BottomCollectionViewCell {
        cell.contentView.backgroundColor = UIColor.orange
        cell.backgroundColor = UIColor.orange
   }

  if let preViousSelectedcell = collectionView.cellForItem(at: 
  selectedIndexPath) as? BottomCollectionViewCell {

     preViousSelectedcell.contentView.backgroundColor=UIColor.purple
     preViousSelectedcell.backgroundColor = UIColor.purple
 }
 selectedIndexPath = indexPath


}

Upvotes: 2

Views: 1334

Answers (1)

Ganesh Manickam
Ganesh Manickam

Reputation: 2139

while scrolling cells are reused that time cellForItemAt will call so you need to change some modification in your code

func collectionView(_ collectionView: UICollectionView, 
didSelectItemAt indexPath: IndexPath) {
 selectedIndexPath = indexPath
 YOUR_COLLECTION_VIEW.reloadData()
}

and add below lines inside your collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)

if indexPath ==  selectedIndexPath {
     cell.contentView.backgroundColor=UIColor.purple
     cell.backgroundColor = UIColor.purple
} else {
     cell.contentView.backgroundColor = UIColor.orange
     cell.backgroundColor = UIColor.orange
}

Hope this will help you

Upvotes: 6

Related Questions