Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 475
diogo.appDev Avatar asked Oct 24 '13 09:10

diogo.appDev


2 Answers

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];
}
like image 131
Calin Chitu Avatar answered Oct 16 '22 23:10

Calin Chitu


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];
    }
}
like image 23
CyberMew Avatar answered Oct 17 '22 00:10

CyberMew