【问题标题】:Deselect default selected cell on selecting any other cell in UICollectionview在 UICollectionview 中选择任何其他单元格时取消选择默认选定单元格
【发布时间】:2021-08-24 07:11:21
【问题描述】:

使用 UICollectionView 显示日历,我已默认选择今天的日期,并希望在选择任何其他日期时取消选择该日期。以下是我的代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalenderCell", for: indexPath) as! CalenderCollectionViewCell
    
    cell.lblDayName.text = arrCalendarDays[indexPath.item]
    cell.lblDate.text = arrCalendarOnlyDate[indexPath.item]
    
    if indexPath.item == 0 {
        if !isTodayDate {
        cell.isSelected = true
        } else {
            cell.isSelected = false
        }
    }
    
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    isTodayDate = true

// Tried below code but not working
   /* collectionViewWeekCalendar.indexPathsForSelectedItems?
        .forEach {
            self.collectionViewWeekCalendar.deselectItem(at: $0, animated: false) }
    */
    let selectedCell:UICollectionViewCell = collectionViewWeekCalendar.cellForItem(at: indexPath)!
    selectedCell.isSelected = true
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let selectedCell:UICollectionViewCell = collectionViewWeekCalendar.cellForItem(at: indexPath as IndexPath)!
    selectedCell.isSelected = false
}

问题是,在选择任何其他日期时,今天的选定日期不会取消选择。请指导。

【问题讨论】:

    标签: ios swift uicollectionview calendar uicollectionviewcell


    【解决方案1】:

    hacky 和最简单的方法(我认为) 使用选定的索引

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CalenderCell", for: indexPath) as! CalenderCollectionViewCell
    
      cell.lblDayName.text = arrCalendarDays[indexPath.item]
      cell.lblDate.text = arrCalendarOnlyDate[indexPath.item]
    
      if sellectedIndex == indexPath {
        cell.isSelected = true
      } else {
        cell.isSelected = false
      }
    
      return cell 
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndex = indexPath
        collectionView.reloadData()
    }
    

    一开始,

    set selectedIndex = today date Index
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 2014-07-17
      相关资源
      最近更新 更多