我正在模态地呈现一个 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/