Imran Imran - 4 months ago 106
Objective-C Question

UICollectionView CustomCell- Not able to deselect already Selected Cell

I m using

collectionCell
to select and deselect image on
collectionCell
. But when i click on selected cell , it wont get deselected.

it change only, when i select any other cell in collection list.

My Code

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

BICollectionCell *cell = (BICollectionCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"BICollectionCell" forIndexPath:indexPath];
[cell setSelected:YES];
[self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];

<----Label Values--->
return Cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

BICollectionCell *cell = (BICollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[cell.imgSelectedImage setImage:[UIImage imageNamed:@"vs_tick.png"]];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

BICollectionCell *cell = (BICollectionCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
[cell.imgSelectedImage setImage:nil];
}

Answer

If you want to change image on selection of cell and if cell is already selected and you want to deselect it, then you can change your code like this

First Create one instance property selectedIndexPath like this

@property NSIndexPath *selectedIndexPath;

After that change your cellForItemAtIndexPath like this

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    BICollectionCell *cell = (BICollectionCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"BICollectionCell" forIndexPath:indexPath];
    [cell setSelected:YES];
    [self.collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    if (self.selectedIndexPath == indexPath) {
        [cell.imgSelectedImage setImage:[UIImage imageNamed:@"vs_tick.png"]];
    }
    else {
        [cell.imgSelectedImage setImage:nil];
    }
    <----Label Values--->
    return Cell;
}

Now in didSelectItemAtIndexPath check for already selected cell like this

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectedIndexPath == indexPath) {
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        self.selectedIndexPath = nil;
    }
    else {
        self.selectedIndexPath = indexPath;
    }        
    [self.collectionView reloadData];
}

Note - Remove your didDeselectItemAtIndexPath method there is no need of this now.