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



当重新选择第一个项目时,它工作得很好(它被取消选择),但我有问题在使用"集合时。allowmultiplesselection = true"当选择第二项或第三项时,它会为我描绘出所有内容(这是我不想要的)。任何解决方案,能够取消选择上一个项目,当我选择新项目,改变取消选择的项目(上)?在斯威夫特。

听起来你的目标是:

  • 只允许一个单元格每次选择
  • 还允许轻击选定单元格以取消选中

如果是,您可以使用几种不同的方法。

1 -设置采集视图.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)
}
}
}
}

最新更新