diogo.
diogo.

Reputation: 1113

Highlight cells in CollectionView

I'm building an app in iOS and I want the Cells in my CollectionView to highlight when touched, pretty much like the normal buttons. How can I achieve this in the didSelectItemAtIndexPath:(NSIndexPath *)indexPath method?

Upvotes: 6

Views: 14901

Answers (4)

lily
lily

Reputation: 11

why can not change the background color through the cocoa pods?I new a user-defined collectionView cell class`

   - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        CHSMenuControlCell *cell = (CHSMenuControlCell*)[collectionView  cellForItemAtIndexPath:indexPath];
        cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; //     //cell.lblImgTitle.text = @"xxx";
    }

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

Upvotes: 0

CyberMew
CyberMew

Reputation: 1421

If you subclassed the cell class, put this in your .m file

- (void)setSelected:(BOOL)selected
{
    if(selected)
    {
        self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.5];
    }
    else
    {
        self.backgroundColor = [UIColor whiteColor];
    }
}

Upvotes: 5

Calin Chitu
Calin Chitu

Reputation: 1099

Try something like this:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    .....
    if (cell.selected) {
        cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; // highlight selection
    }
    else
    {
        cell.backgroundColor = [UIColor clearColor]; // Default color
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell* cell = [collectionView  cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:153/255.0 alpha:1]; //     //cell.lblImgTitle.text = @"xxx";
}

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

Upvotes: 7

Vaisakh
Vaisakh

Reputation: 2927

try this

cell.selectedBackgroundView.backgroundColor = [UIColor greenColor];

Upvotes: 0

Related Questions