ios UICollectionView单元格选择和取消选择问题

时间:2017-11-29 04:46:18

标签: ios uicollectionview swift4 xcode9

我使用UIcollection视图作为我的tabbar 当我水平滚动集合视图时,当我选择新的

时,前一个选定的单元格将不会取消选择

这是我选择单元格并取消选择单元格时更改颜色的代码

  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 个答案:

答案 0 :(得分:4)

当滚动单元格被重用时cellForItemAt将调用,因此您需要更改代码中的某些修改

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
}

希望这会对你有所帮助