Cell Selection in CollectionView

I am creating an application in iOS, and I want the cells in my CollectionView to be highlighted when touched, much like regular buttons. How can I achieve this in the didSelectItemAtIndexPath: (NSIndexPath *) indexPath method ?

+6
source share
4 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]; } 
+7
source

If you subclass 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]; } } 
+5
source

try it

 cell.selectedBackgroundView.backgroundColor = [UIColor greenColor]; 
0
source

Why can't I change the background color with cocoa pods? I am a new custom class cellView 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]; } 
0
source

Source: https://habr.com/ru/post/956624/


All Articles