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

  • September中选择4,5,然后移至August/July/November(在本月中可能选择其他日期或不选择其他日期)
  • 然后返回September。在September中,我想显示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/

    10-15 10:16
    查看更多