ios - UICollectionViewCell 在第一次点击时取消选择预先选择的单元格

标签 ios swift uicollectionview uicollectionviewcell

我正在模态地呈现一个 viewcontroller,它托管一个 viewcollection,其中“预选”单元格根据 segue 上传递的数据格式化为不同的背景颜色。

当我点击这些“预选”单元格之一时,需要点击两次才能触发 didDeselectItemAt 委托(delegate)方法。我理解为什么在调试时会发生这种情况,虽然不同颜色的单元格不一定在选定状态下被识别。 有没有办法首先为“预选”单元格触发 didDeselectItemAt

我已经尝试在委托(delegate)方法 cellForItemAt 中合并,作为更改单元格背景颜色的条件语句的一部分,设置 cell.isSelected = true .同样在同一个委托(delegate)方法中,我也尝试调用一个函数,该函数将使用这些“预选”单元格的 indexPaths 调用委托(delegate)方法 didSelectItemAt。两者产生相同的结果。

以下是(缩写的)相关代码片段:

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

    if preselectedDataPoints { cell.backgroundColor = blue }
    else { cell.backgroundColor = white }
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = blue
    preselectedDataPoints.append(newDataPoint)
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.backgroundColor = white
    preselectedDataPoints.remove(at: existingDataPoint)
}

最佳答案

如果预选单元格,则在 didSelectItem 中以编程方式调用 collectionView.deselectItem(at: indexPath, animated: true)

推荐码

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if preselectedDataPoints { 
       collectionView.deselectItem(at: indexPath, animated: true) 
    }else{
       let cell = collectionView.cellForItem(at: indexPath)
       cell?.backgroundColor = blue
       preselectedDataPoints.append(newDataPoint)
    }  

}

在deSelect方法中直接调用你需要执行的任何代码

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    if preselectedDataPoints { 
       let cell = collectionView.cellForItem(at: indexPath)
       cell?.backgroundColor = white
       preselectedDataPoints.remove(at: existingDataPoint)
    }else{
       let cell = collectionView.cellForItem(at: indexPath)
       cell?.backgroundColor = blue
       preselectedDataPoints.append(newDataPoint)
    }  

}

关于ios - UICollectionViewCell 在第一次点击时取消选择预先选择的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435625/

相关文章:

iphone - iOS:将 6x6 400x300px 图像添加到一张合成图像

ios - 解析 : How to know whether a image file has been cached using PFImageView?

javascript - 延迟隐藏移动地址栏

swift - MacOS NSWorkspace.shared.open "The application can’ 无法打开。 -50"

ios - UILabel - 如何在 Swift 3 中的行之间添加空格

ios - 使用 setNeedsDisplay

ios - UICollectionView ImageView 问题

ios - 如何向 Collection View 添加标签

ios - 用图像填充 UICollectionView 返回 nil : Swift 2

ios UICollectionView 以编程方式删除标题