Highlight cells in CollectionView

diogo.appDev picture diogo.appDev · Oct 24, 2013 · Viewed 14.8k times · Source

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?

Answer

Calin Chitu picture Calin Chitu · Oct 24, 2013

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