[英]UICollectionView didDeselectItemAtIndexPath doesn't get cell
I have a simple collectionView, and with didSelectItemAtIndexPath
and didDeselectItemAtIndexPath
I change cell's background color. 我有一个简单的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];
}
All works fine, but if I select a cell, scroll the list (my selected cell go out of screen) and I select another, in didDeselectItemAtIndexPath
my "cell" variable is nil. 一切正常,但是如果我选择一个单元格,则滚动列表(我选择的单元格不在屏幕上),然后选择另一个,在
didDeselectItemAtIndexPath
我的“单元格”变量为nil。 Why? 为什么?
NB: only when the selected cell go out of screen 注意:仅当所选单元格不在屏幕上时
Simply logic behind cell selected and deselected in proper way: 以适当的方式简单地选择和取消选择单元格后面的逻辑:
ViewController.h
ViewController.h
int selectedIndex;
ViewController.m
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.