[英]UICollectionView - didDeselectItemAtIndexPath not called if cell is selected
[英]UICollectionView didDeselectItemAtIndexPath doesn't get cell
我有一個簡單的collectionView,並使用didSelectItemAtIndexPath
和didDeselectItemAtIndexPath
更改單元格的背景色。
- (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.