我正在尝试实现此功能:在我的应用程序中,如果我在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()
    }
}

nilPath 只是 IndexPath(item:-1,section:0),但这没关系,因为甚至没有调用 collectionView(_ collectionView:UICollectionView,didDeselectItemAt indexPath:IndexPath)。我的CollectionView具有allowSelection = true和allowMultipleSelection = false属性。感谢您的帮助。

最佳答案

如果只应同时选择一个单元格,建议将当前选择的索引路径放入实例变量中(nil表示未选择任何内容)

var selectedIndexPath : IndexPath?

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
}

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)
}

仅当要显式取消选择单元格时才需要didDeselectItemAt

09-11 05:05
查看更多