【问题标题】:UICollectionView issue with Select/Deselect cell选择/取消选择单元格的 UICollectionView 问题
【发布时间】:2018-03-26 13:15:16
【问题描述】:

大家好,我在选择集合中的单元格时遇到问题。 当然,为了管理选择和取消选择,我提供了委托方法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];    
}

【问题讨论】:

    标签: ios uicollectionview uicollectionviewcell nsindexpath


    【解决方案1】:

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

    第一

    • 您不应在 didSelectItemAtIndexPathdidDeselectItemAtIndexPath 方法中更改 textColorday。因为当您滚动 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;
      }
      

    更多细节可以查看我的demo repo here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 2021-08-24
      • 2017-03-04
      • 2019-10-24
      相关资源
      最近更新 更多