繁体   English   中英

从 collectionView 中选择一个项目后,如何取消选择另一个项目?

[英]how can you deselect the other item once you have selected an item from the collectionView?

在斯威夫特。 重新选择第一项时,它运行良好(已取消选择),但是我有一个问题:在选择“ collection.allowsmultipleselection = true”时,选择第二个或第三个项目时,它会为我绘制所有东西(我不想要)。 任何能够取消选择上一个项目以及当我选择更改取消选择的项目(上一个)的新项目时的解决方案? 迅速。

听起来你的目标是:

  • 一次只允许选择一个单元格
  • 还允许点击选定的单元格以取消选择它

如果是这样,您可以通过几种不同的方式进行操作。

一设置集合视图.allowsMultipleSelection = false并实现shouldSelectItemAt

func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
    // get array of already selected index paths
    if let a = collectionView.indexPathsForSelectedItems {
        // if that array contains indexPath, that means
        //  it is already selected, so
        if a.contains(indexPath) {
            // deselect it
            collectionView.deselectItem(at: indexPath, animated: false)
            return false
        }
    }
    // no indexPaths (cells) were selected, so return true
    return true
}

两组.allowsMultipleSelection = true并实现didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // get array of already selected index paths
    if let a = collectionView.indexPathsForSelectedItems {
        // for each path in selected index paths
        a.forEach { pth in
            // if it is NOT equal to the tapped cell
            if pth != indexPath {
                // deselect it
                collectionView.deselectItem(at: pth, animated: false)
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM