ios - 在 didSelectItemAt 中选择单元格时取消选择 cellForItemAt 中的单元格

标签 ios swift uicollectionview uicollectionviewcell

我有一个变量 selectedIndexPath,它获取从上一个 View Controller 中选择的 indexPath。我在当前 View Controller 的 collection view 中为 cell 获取所需的 backgroundColor。但是当我在 Collection View 中选择另一个单元格时,先前 View Controller 的选定单元格保持不变而没有被取消选择。所以,现在我有两个具有背景颜色的单元格。以下是我的代码

var selectedIndexPath = IndexPath()

override func viewDidLoad() {
    super.viewDidLoad()
    self.collectionView.allowsMultipleSelection = false
    self.collectionView.allowsSelection = true
}

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

    if (indexPath == selectedIndexPath)
    {
        cell.backgroundColor = UIColor.white
    }
    else
    {
        cell.backgroundColor = UIColor.clear
    }

    collectionView.allowsMultipleSelection = false
    return cell
}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.white
    collectionView.allowsMultipleSelection = false 
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
{
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = UIColor.clear
    collectionView.allowsMultipleSelection = false
}

当我在 didSelectItemAt选择 新单元格时,如何取消选择 cellForItemAt 中的单元格。提前致谢。

最佳答案

首先在 Interface Builder 中设置 allowsMultipleSelection 并删除代码中所有多余的设置

您必须更新 selectedIndexPath 变量。直接操作单元格总是一个坏主意。
重新加载细胞更可靠。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    guard selectedIndexPath != indexPath else { return }
    let indexPathsToUpdate = [selectedIndexPath, indexPath]
    selectedIndexPath = indexPath            
    tableView.reloadRows(at: indexPathsToUpdate, with: .none)
}


func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)
{
    guard selectedIndexPath == indexPath else { return }
    selectedIndexPath = IndexPath()
    tableView.reloadRows(at: [indexPath], with: .none)
}

只有一个问题:如果您想要一个空的选择,您必须将 selectedIndexPath 声明为可选的并正确处理它。

关于ios - 在 didSelectItemAt 中选择单元格时取消选择 cellForItemAt 中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679128/

相关文章:

swift - 如何在行 Collection View 中创建 2 个单元格

ios - 每个 CollectionView Cell 都有独特的计时器

ios - 尝试在时间间隔后清除粘贴板

objective-c - dispatch_queue_t SerialQueue如何检查是否仍在运行。 ios GCD

objective-c - 如何在页面中添加评论框?

ios - 在 swift 扩展中重载 NSDictionary getter

ios - 如何以编程方式检查应用程序商店区域/国家?

Swift DispatchQueue 与 Firebase 同步

ios - 如何在导航栏 Swift 右侧添加自定义 View ?

arrays - 如何在 Swift 的 View Controller 类中与 Collection View 委托(delegate)共享数据