ios - 切换到其他页面时取消选择选定的单元格

标签 ios swift uicollectionview

我使用 UICollectionView 制作了一个自定义日历。从日历中选择一些日期并前进到下个月,然后再次返回上个月,取消选择所选项目。也许它发生在可重复使用的电池上。我怎么解决这个问题。 为了更好地理解我想要什么:

  1. 9 月 我选择 4,5 然后移动到 8 月/7 月/11 月(在这个月可能选择其他日期或不)
  2. 然后返回到 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/

相关文章:

ios - 核心数据和 iCloud

ios - Swift 动态转换失败 UIPageViewController

ios - 如何在同一容器中解码 DynamicKeys 和 CodingKeys?

ios - CollectionView循环显示项目分页

ios - 如何将元素向量映射到 UICollectionView 网格中?

ios - 在 Xcode 10 中对 Xcode 项目文件进行排序,以清除项目文件更改

ios - 滚动时取消 UITableView 中的动画

arrays - 取消选择 Collection View 中的项目并将其从无效的数组中删除

ios - Swift AVAudioEngine AVAudioPCMBuffer 到 PowerLevel

ios - 具有模拟器支持的 Core Image 着色器语言转换为 Metal