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

标签 ios uicollectionview swift4 xcode9

我使用 UIcollection View 作为我的标签栏 当我水平滚动 Collection View 时,当我选择新的单元格时,前一个选定的单元格不会取消选择

这是我选择一个单元格和取消选择一个单元格时改变颜色的代码

  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 将调用,因此您需要更改代码中的一些修改

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 单元格选择和取消选择问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545220/

相关文章:

swift - swift 中 "event listeners"的想法如何分为 Action 和协议(protocol)?

ios - Firebase Google Sign In (iOS) - 从未调用过 GIDSignInUIDelegate 方法

ios - 计算大于360度的旋转角度而不是倾斜角度

ios - collectionView 中的内容大小错误

ios - UICollectionView + SDWebImage + 单元格重用

ios - CollectionView-将pdf文件拖放到collectionView上(loadObject(ofClass :)无法正常工作)

ios - 修复了具有流式布局的 UICollectionView 中项目之间的间距

ios - 在 swift 4.0 中查找 realm 的 schemaVersion

ios - 带有 Django 后端的 PhoneGap

iphone - 我需要将背景音乐添加到我的应用程序的主视图中