![](/img/trans.png)
[英]iOS (Swift): Collection View indexPath(for: cell) is nil for non visible cell
[英]Not able to loop all visible and non visible cell in collection view and change the cell property
我有一个名为isSelected = bool
的集合视图单元格属性。 因此,默认情况下,第一项将被选中,因此我在 viewdidappear 出现在屏幕上之后将isSelected = true
传递给第一项。
现在在我的 didselect 方法中,如果我 select 任何单元格,该特定单元格属性应该是isSelected = true
并且之前的单元格属性应该是 false。
现在问题只出在我可以迭代并设置isSelected = false
的可见单元格上。 我需要循环所有可见和不可见的单元格,我需要更改属性,并且我需要再次处理要更改的选定单元格属性值。
我需要重写我的逻辑而不是使用两个实例,我改变的问题就像。 如果我 select 我的可见单元格中的任何单元格并设置为 true。 如果我再次滚动到不可见的单元格和 select 任何变为 true 的单元格。
所以这意味着我的两个单元格属性有isSelected = false
。 我该如何改变它。
更新:
var selectedChartIndex: Int = -1
if self.selectedChartIndex == indexPath.row {
(cell as? userCell)?.selectedCell = true
} else {
(cell as? userCell)?.selectedCell = false
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: IndexPath(row: selectedChartIndex, section: 0)) as? userCell {
cell.selectedCell = false
}
(collectionView.cellForItem(at: indexPath) as? userCell)?.selectedCell = true
selectedChartIndex = indexPath.row
}
如果我这样做:
if let cell = collectionView.cellForItem(at: IndexPath(row: selectedChartIndex, section: 0)) as? userCell {
cell.selectedCell = false
}
那么如果我 select 任何单元格都没有突出显示,那很好。 但是当我连续滚动集合视图时,选定的项目会突出显示
在 controller 中声明一个属性来保持选中的索引路径
var selectedIndexPath : IndexPath?
在cellForItemAt
中设置单元格的选定 state
if let selectedPath = selectedIndexPath, selectedPath == indexPath {
cell.selectedCell = true
} else {
cell.selectedCell = false
}
在didSelectItem
中取消selectedIndexPath
处的项目,select 当前 indexPath 处的项目并更新selectedIndexPath
if let currentPath = selectedIndexPath, let cell = collectionView.cellForItem(at: currentPath) as? UserDataCell {
cell.selectedCell = false
}
(collectionView.cellForItem(at: indexPath) as? UserDataCell)?.selectedCell = true
selectedIndexPath = indexPath
您只需使用一个数组,该数组为每个单元格保存值 true/false 并将该值发送到 cellForIndexPath 和每个 didSelect 上,您必须更改数组中的值并重新加载集合视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.