Home > DeveloperSection > Forums > How to change the background color of UICollectionView cell in iOS?
Eric Martell
Eric Martell

Total Post:9

Posted on    December-23-2015 6:02 AM

 iPhone iPhone  Ios  Objective C 

 1 Reply(s)
 3303  View(s)
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.

Tarun Kumar

Total Post:214

Posted on    December-23-2015 10:27 PM

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];

Don't want to miss updates? Please click the below button!

Follow MindStick