我使用 UICollectionView
制作了一个自定义日历。从日历中选择一些日期并前进到下个月,然后再次返回上个月,取消选择所选项目。也许它发生在可重复使用的电池上。我怎么解决这个问题。
为了更好地理解我想要什么:
- 从
9 月
我选择 4,5 然后移动到8 月/7 月/11 月
(在这个月可能选择其他日期或不) - 然后返回到
9 月
。在9 月
,我想将 4,5 显示为选中状态
我尝试使用 didSelectItemAt
indexPath,但是当返回到 September
时,所选项目被取消选择
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? CalendarDateRangePickerCell {
if cell.isSelected == true {
cell.backgroundColor = .blue
cell.label.textColor = .white
cell.isUserInteractionEnabled = true
}
selectedDate = cell.date!
}
}
最佳答案
首先创建一个选定单元格的数组。如果您使用模型将数据设置为单元格,则可以创建选定模型的数组。或者您可以创建一个选定行的数组。
假设您正在使用模型。
var selectedDates: [DateModel] = []
然后
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? CalendarDateRangePickerCell {
selectedDate = cell.date!
if !selectedDates.contains(dataSourceModel[indexPath.row]) {
selectedDates.append(dataSourceModel[indexPath.row])
}
}
}
然后在你的 cellForItem
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if selectedDates.contains(dataSourceModel[indexPath.row]) {
cell.isSelected = true
}
}
还要确保在未选中时删除模型
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if selectedDates.contains(dataSourceModel[indexPath.row]) {
selectedDates.remove(dataSourceModel[indexPath.row])
}
}
*可能包含一些语法错误,但您可以按照此路径到达您想要的位置。
关于ios - 切换到其他页面时取消选择选定的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57688818/