HOW TO CHANGE THE BACKGROUND COLOR OF UICOLLECTIONVIEW CELL IN IOS?

Eric Martell

Total Post:9

Points:63
Posted by  Eric Martell
 3507  View(s)
Ratings:
Rate this:

I have created an application using UICollectionView, and adding some images into the collection view cell.
Now I want to change the cell background color whenever the element is tapped.
I have tried by this code:

-(void) collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    //change color when tapped
}

-(void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    //change back on touch up
}

It works but it will change only when I keep my finger for a bit longer time.
Can you tell me is there any functionality similar like in UITableViewCell willSelectItemAtIndexPath: method.
Please suggest me any solution.

  1. Tarun Kumar

    Post:214

    Points:1642
    Re: How to change the background color of UICollectionView cell in iOS?

    If you want to change the background with different color on different cell selection, then you can try collection view method didSelectedItemAtIndexPath: and didDeselectItemAtIndexPath: .
    Here is both example:

    - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        cell.backgroundColor = [UIColor yellowColor];
    }

     

    - (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!