Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The way you're trying to do this is incorrect. You need to keep a reference to the selected cell or cells in a property. In this example, I use an array to hold index paths of the selected cells, then check whether the index path passed in to cellForItemAtIndexPath is contained in that array. I unselect the cell if you click on one that's already selected:</p> <pre><code>@interface ViewController () @property (strong,nonatomic) NSArray *theData; @property (strong,nonatomic) NSMutableArray *paths; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.paths = [NSMutableArray new]; self.theData = @[@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight"]; [self.collectionView registerNib:[UINib nibWithNibName:@"CVCell" bundle:nil] forCellWithReuseIdentifier:@"cvCell"]; UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init]; [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical]; [self.collectionView setCollectionViewLayout:flowLayout]; } -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.theData.count; } -(CVCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cvCell"; CVCell *cell = (CVCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; cell.backgroundColor = [UIColor whiteColor]; cell.label.text = self.theData[indexPath.row]; if ([self.paths containsObject:indexPath]) { [cell.iv setHidden:NO]; // iv is an IBOutlet to an image view in the custom cell }else{ [cell.iv setHidden:YES]; } return cell; } -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { if ([self.paths containsObject:indexPath]) { [self.paths removeObject:indexPath]; }else{ [self.paths addObject:indexPath]; } [self.collectionView reloadItemsAtIndexPaths:@[indexPath]]; } - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { return CGSizeMake(150, 150); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload