选择/取消选择单元格的UICollectionView问题

时间:2018-03-26 13:15:16

标签: ios uicollectionview uicollectionviewcell nsindexpath

大家好我在我的收藏中选择细胞时遇到问题。 当然,为了管理选择和取消选择,我提供了委派的方法didSelectItemAtIndexPathdidDeselectItemAtIndexPath

一切正常但我有一个我无法解决的问题。简而言之,当我选择一个单元格时,我希望有可能通过重新选择单元格来取消选择最后一个单元格...例如

我将使用单元格的名称来让您更好地理解我的问题

用户选择单元格“22”取消选择。我希望用户再次重新选择单元格 22 并取消选择。

我尝试使用allowMultipleSelection = YES这似乎是我喜欢的系统,但问题是没有重新选择单元格,所有其他条目都被选中,所以这是错误的...我怎么能解决这个问题...... ??

这是我用于选择和取消选择单元格的代码

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    SmartCalendarDayCell *calendarDayCell = (SmartCalendarDayCell *)[self.dayCollectionView cellForItemAtIndexPath:indexPath];
    calendarDayCell.day.textColor = [UIColor colorWithHexString:@"#D97E66" setAlpha:1];
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

    SmartCalendarDayCell *calendarDayCell = (SmartCalendarDayCell *)[self.dayCollectionView cellForItemAtIndexPath:indexPath];
    calendarDayCell.day.textColor = [UIColor lightGrayColor];    
}

1 个答案:

答案 0 :(得分:1)

据我了解,您希望您的collectionView一次只能选择1个单元格,如果再次单击选定的单元格,则会取消选择该单元格。如果我误解了什么,请告诉我。

<强>第一

  • 您不应该在textColorday方法中更改didSelectItemAtIndexPath didDeselectItemAtIndexPath。因为当您滚动collectionView时,将重复使用单元格,并且某些单元格的day颜色会出错。
  • 要解决此问题,请使用property selected of UICollectionViewCell

    SmartCalendarDayCell.m

    - (void)setSelected:(BOOL)selected {
      [super setSelected:selected];
    
      if (selected) {
        self.day.textColor = [UIColor colorWithHexString:@"#D97E66" setAlpha:1];
      } else {
        self.day.textColor = [UIColor lightGrayColor];
      }
    }
    

<强>第二

  • 要取消选择所选单元格,您应该使用collectionView:shouldSelectItemAtIndexPath:方法检查并执行此操作。

    - (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath {
      if ([collectionView.indexPathsForSelectedItems containsObject:indexPath]) {
        [collectionView deselectItemAtIndexPath:indexPath animated:NO];
        return NO;
      }
    
      return YES;
    }
    

有关详细信息,请查看我的演示报告here

相关问题