I have a simple collectionView, and with didSelectItemAtIndexPath
and didDeselectItemAtIndexPath
I change cell's background color.
- (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. Why?
NB: only when the selected cell go out of screen
Simply logic behind cell selected and deselected in proper way:
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.