sanjeet
sanjeet

Reputation: 1510

UICollectionViewCell single selection

guys can someone guide me with uicollectionview, i am setting border color to cell, now my requirement is when i tap on cell it border color will be red, now i m tapping on second cell now second cell border will be red and first cell border will be clearcolor.

UICollectionViewCell *selectedCell =
[collectionView cellForItemAtIndexPath:indexPath];

selectedCell.contentView.backgroundColor = nil;
[selectedCell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
[selectedCell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
[selectedCell.contentView.layer setBorderWidth:3.0f];

const NSTimeInterval kAnimationDuration = 0.20;
[UIView animateWithDuration:kAnimationDuration animations:^{
    [selectedCell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
    selectedCell.alpha = 0.0f;
} completion:^(BOOL finished) {
    [UIView animateWithDuration:kAnimationDuration animations:^{
        [selectedCell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
        selectedCell.alpha = 1.0f;
    }];
}];

Upvotes: 1

Views: 1587

Answers (2)

Viktor Kucera
Viktor Kucera

Reputation: 6335

Use didSelectItemAtIndexPath and save the IndexPath of selected cell. Here is my code which I am using for same thing you requested. Just substitute..

- (void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ProductCell *selectedCell = (ProductCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [selectedCell setBackgroundColor:[UIColor redColor]];

    if (self.selectedIndexPath)
    {
        ProductCell *deselectedCell = (ProductCell *)[collectionView cellForItemAtIndexPath:self.selectedIndexPath];
        [deselectedCell setBackgroundColor:[UIColor clearColor]];
    }

    self.selectedIndexPath = indexPath;
}

Upvotes: 0

sanjeet
sanjeet

Reputation: 1510

I got the solution.

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

UICollectionViewCell *selectedCell =
[collectionView cellForItemAtIndexPath:indexPath];

selectedCell.contentView.backgroundColor = nil;
[selectedCell.contentView.layer setBorderColor:[UIColor redColor].CGColor];
[selectedCell.contentView.layer setBorderWidth:3.0f];   
}

and add this delegate method too

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *deselectedCell =
[collectionView cellForItemAtIndexPath:indexPath];
deselectedCell.contentView.backgroundColor = nil;
[deselectedCell.contentView.layer setBorderColor:[UIColor clearColor].CGColor];
[deselectedCell.contentView.layer setBorderWidth:3.0f];
}

Upvotes: 2

Related Questions