Search code examples
ios8uicollectionviewnsindexpath

IndexPath for Selected Cell UICollectionView


I'm currently working on a UICollectionView showing various cells ...

So far so good, but I have problems with the selection of the cell ... For example, I implemented the method of selection like this:

    - (Void)collectionView:(UICollectionView *) collectionView didSelectItemAtIndexPath:(NSIndexPath *) indexPath {
        

          UICollectionViewCell theCell * = (UICollectionViewCell *) [CollectionView cellForItemAtIndexPath: indexPath];

         theCell.backgroundColor = [UIColor orangeColor];
        
}

The problem is that in addition to making Orange the selected cell also creates other selections when I browse the collection view ..

Example: select the cell number 7 and also automatically select the cell number 14 ... Obviously I did not need this but I would like it to remain selected only the cell number 7

Where am I doing wrong? there 's something wrong with my indexPath?


Solution

  • in method

    (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    

    add sth like this:

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"yourCelId" forIndexPath:indexPath];
    
    
    if (cell.selected) {
         cell.backgroundColor = [UIColor orangeColor]; 
    } else {
         cell.backgroundColor = [UIColor clearColor];
    }   
    

    It's happens because cells are reused and you have to reset all values that could be changed.