我有一个变量 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/