繁体   English   中英

UICollectionView didDeselectItemAtIndexPath不获取单元格

[英]UICollectionView didDeselectItemAtIndexPath doesn't get cell

我有一个简单的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我的“单元格”变量为nil。 为什么?

注意:仅当所选单元格不在屏幕上时

以适当的方式简单地选择和取消选择单元格后面的逻辑:

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];
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM