ios UICollectionView cell selecting and deselecting issue

人盡茶涼 提交于 2021-01-28 08:23:04

问题


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


}

回答1:


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



来源:https://stackoverflow.com/questions/47545220/ios-uicollectionview-cell-selecting-and-deselecting-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!