如何允许选择和取消选择多个UICollectionViewCells?

时间:2018-11-25 20:06:12

标签: ios swift uicollectionview uicollectionviewcell

我有一个UICollectionView(带有.allowsMultipleSelection = true),我想要它,以便每当我点击一个单元格时,它都会改变颜色,而当我再次点击它时,它会恢复为原来的颜色。 。我了解UICollectionViewCell具有isSelected属性,因此我尝试通过操作来更改颜色。

override var isSelected: Bool {
        didSet {
            if isSelected == false {
                contentView.backgroundColor = .lightGray
                roleLabel.textColor = .gray
            } else {
                contentView.backgroundColor = .gray
                roleLabel.textColor = .black
                print("selected")
            }
        }
    }

我包含相关集合视图的视图控制器类已定义didSelectItemAt。但是,每当我点击该单元格时,每次都会打印“选定”-表示无论我在该单元格上轻击了多少次,它每次仍将isSelected设置为true-颜色不变。为什么会这样?

1 个答案:

答案 0 :(得分:0)

您必须将所选单元格存储在数组中。例如,仅将所选单元格的索引路径存储在数组中,然后检查数组中是否已存在索引路径,这意味着它已被选中。

var slectedCell = [IndexPath]()

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


        if slectedCell.contains(indexPath) {
            cell.backgroundColor = UIColor.gray
            slectedCell = slectedCell.filter { $0 != indexPath }
        }
        else {
            slectedCell.append(indexPath)
            cell.backgroundColor = UIColor.lightGray
        }

    }


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if slectedCell.contains(indexPath) {
            cell.backgroundColor = UIColor.gray
        }
        else {
            cell.backgroundColor = UIColor.lightGray
        }


    }