无法取消选择collectionView中的项目

时间:2018-12-18 12:56:17

标签: ios swift collectionview didselectrowatindexpath pfcollectionviewcell

我有collectionView。在第一次启动时,我将第一项的颜色更改为黑色。问题是当我选择另一个项目时,我希望它变成黑色,而第一个项目变成白色。我使用didSelectItemAtIndexPath和didDeselectItemAtIndexPath,但是如果我不单击第一个项目,那么单击另一个项目时就无法更改其颜色。有人可以帮我吗?

3 个答案:

答案 0 :(得分:1)

您可以按照以下方式进行操作。

覆盖如下所示的UICollectionViewCell类中的方法

override var isSelected: Bool{
    didSet{
        if(self.isSelected){
            yourView.backgroundColor = YourSelectedColor

        }else{
            yourView.backgroundColor = YourUnSelectedColor
        }
    }
}

无需在didSelectItemAt或didDeSelectItemAt方法中进行任何操作。

答案 1 :(得分:0)

您的数据源数组中的元素应该以某种方式知道单元格的当前状态。例如,您可以拥有自定义对象的属性:

var isSelected: Bool = false

didSelectItemAt方法中,首先将每个元素的isSelected属性更改为false,然后将所选元素集true更改为collectionView

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    dataSourceArray.forEach { $0.isSelected = false }
    dataSourceArray[indexPath.row] = true
    collectionView.reloadData()
}

然后在cellForRowAt的{​​{1}}中更改backgroundColor取决于数据源数组中某些元素的cell属性

isSelected

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    ...
    cell.backgroundColor = dataSourceArray[indexPath.row] ? .black : .white
    ...
}

或者,您可以仅将var selectedIndexPath = IndexPath? 所选单元格另存为全局变量

indexPath

然后在func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedIndexPath = indexPath collectionView.reloadData() } 中,如果cellForRowAt等于backgroundColor,则可以根据条件设置单元格的indexPath

selectedIndexPath

答案 2 :(得分:0)

设置选定的索引路径并根据选定的索引路径重新加载收集视图。

class CollectionViewController: UICollectionViewController {

var selectedIndexPath : IndexPath?

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
    if indexPath == selectedIndexPath {
        cell.backgroundColor = UIColor.black
    } else {
        cell.backgroundColor = UIColor.white
    }
    return cell
}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedIndexPath = indexPath
    collectionView.reloadData()
}

}

相关问题