ios UICollectionView 单元格选择和取消选择问题 [英] ios UICollectionView cell selecting and deselecting issue

查看:58
本文介绍了ios UICollectionView 单元格选择和取消选择问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 UIcollection 视图作为我的标签栏当我水平滚动集合视图时,当我选择新的单元格时,上一个选定的单元格不会取消选择

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


}

推荐答案

在重复使用滚动单元格时 cellForItemAt 将调用,因此您需要对代码进行一些修改

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()
}

并在您的 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
}

希望对你有帮助

这篇关于ios UICollectionView 单元格选择和取消选择问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆