【问题标题】:Deselect and change background of other cells in collection view when one cell is selected选择一个单元格时,取消选择并更改集合视图中其他单元格的背景
【发布时间】:2019-09-17 10:29:48
【问题描述】:

我有一个collectionView,我想一次选择一个单元格。并更改所选单元格的背景。我有一个问题,当我在 didSelectItem() 方法中选择一个单元格时,我之前选择的单元格背景没有改变。

func collectionView(_ collectionView: UICollectionView,didSelectItemAt indexPath: IndexPath) {

    if let cell2 = self.segmentScrollView.cellForItem(at: selectedcellNo!) as? segmentCollectionViewCell {

        //self.segmentScrollView.reloadItems(at: [selectedcellNo!])
        cell2.segmentName.backgroundColor = .white
        cell2.segmentName.textColor = UIColor.init(red: 141/255, green: 0/255, blue: 22/255, alpha: 1.0)            
        self.segmentScrollView.deselectItem(at: selectedcellNo!, animated: true)
    }

    let cell = self.segmentScrollView.cellForItem(at: indexPath) as? segmentCollectionViewCell
    cell?.segmentName.backgroundColor =  UIColor.init(red: 141/255, green: 0/255, blue: 22/255, alpha: 1.0)
    cell?.segmentName.textColor = .white
    let dateValue = self.segmentJSON[indexPath.row]["date"].stringValue
    self.getShows(date: dateValue)
    print("selectedcellNo-now: ",selectedcellNo!)
    self.selectedcellNo! = indexPath
}

【问题讨论】:

  • 添加你目前尝试过的代码。
  • @Ranu Dhurandhar 提供您的试用代码。

标签: swift collectionview


【解决方案1】:

在您的自定义UICollectionViewCell 中,覆盖isSelected 属性并根据didSet 观察者中的选定状态更改backgroundColor,即

class CollectionViewCell: UICollectionViewCell {
    override var isSelected: Bool {
        didSet {
            self.backgroundColor = isSelected ? .red : .white
        }
    }

    //rest of the code...
}

在这种情况下不需要实现didSelectItemAt

【讨论】:

  • 谢谢,我会试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多