UICollectionView didDeselectItemAtIndexPath没有获取单元格

时间:2016-12-21 09:35:51

标签: ios objective-c uicollectionview

我有一个简单的collectionView,并且使用didSelectItemAtIndexPathdidDeselectItemAtIndexPath我更改了单元格的背景颜色。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor lightGrayColor];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.contentView.backgroundColor = [UIColor clearColor];
}

一切正常,但是如果我选择一个单元格,滚动列表(我选择的单元格离开屏幕),我选择另一个,didDeselectItemAtIndexPath我的“单元格”变量为零。 为什么?

注意:仅当所选单元格退出屏幕时

1 个答案:

答案 0 :(得分:0)

以正确的方式选择和取消选择单元格后面的逻辑:

  

ViewController.h

 int selectedIndex;
  

ViewController.m

- (void)viewDidLoad 
{
      [super viewDidLoad];
      selectedIndex = -1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
  {
        static NSString *identifier = @"CollectionCell";
        WalletCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

        if(indexPath.row == selectedIndex)
        {
               cell.selected = YES;
               cell.backgroundColor = [UIColor redColor];
        }
        else
        {
               cell.selected = NO;
               cell.backgroundColor = [UIColor clearColor];
        }
          return cell;
  }


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
     UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
      selectedIndex = (int)indexPath.row;
       cell.backgroundColor = [UIColor redColor];
}

 - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
 {
       UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
       cell.backgroundColor = [UIColor clearColor];
 }
相关问题