选择另一个单元格时不会触发 didDeselectItemAt indexPath

D. *_*nko 2 ios uicollectionview swift

我正在尝试实现此功能:在我的应用程序中,如果我在 UICollectionView 中选择了一个单元格,则边框变为蓝色,如果我选择另一个单元格,则应取消选择之前的单元格,边框应变为透明。我写了一些方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ChatCell

        /* Set some settings */
        if globalSelected[indexPath.item] {
            cell.circleView.layer.borderColor = UIColor.blue.cgColor
        } else {
            cell.circleView.layer.borderColor = UIColor.clear.cgColor
        }

        return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    //Global variable for maintain selection
    global.selectedChatPath = indexPath
    globalSelected[indexPath.item] = true
    collectionView.reloadData()
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    if indexPath != nilPath {
        globalSelected[indexPath.item] = false
        collectionView.reloadData()
    }
}
Run Code Online (Sandbox Code Playgroud)

nilPath只是IndexPath(项目:-1,部分:0) ,但没关系,因为的CollectionView(_的CollectionView:UICollectionView,didDeselectItemAt indexPath:IndexPath)甚至没有叫。我的 CollectionView 具有allowSelection = trueallowedMultipleSelection = false属性。我将不胜感激任何帮助。

vad*_*ian 6

如果应该同时选择一个单元格,我建议将当前选择的索引路径放入实例变量中(nil意味着没有选择任何内容)

var selectedIndexPath : IndexPath?
Run Code Online (Sandbox Code Playgroud)

cellForItemAt设置取决于实例变量的颜色

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ChatCell

    /* Set some settings */
    if let selected = selectedIndexPath, selected == indexPath {
        cell.circleView.layer.borderColor = UIColor.blue.cgColor
    } else {
        cell.circleView.layer.borderColor = UIColor.clear.cgColor
    }

    return cell
}
Run Code Online (Sandbox Code Playgroud)

didSelectItemAt仅重新加载以前和新选定的单元格并设置 selectedIndexPath为新选定的索引路径。这比重新加载整个集合视图更有效。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    //Global variable for maintain selection

    var cellsToReload = [indexPath]
    if let selected = selectedIndexPath {
        cellsToReload.append(selected)
    }
    selectedIndexPath = indexPath
    collectionView.reloadItems(at: cellsToReload)
}
Run Code Online (Sandbox Code Playgroud)

didDeselectItemAt 仅当您想明确取消选择单元格时才需要。