1

So pretty much, when I try to scroll my UICollectionView while I a cell is selected, shown by a thin orange border, when I scroll back a different cell has the border. I read that it had something to do with cell's being reused. Anyways I found some code online, but just been having a hard time adapting it to multiple selection.

Found a solution to this problem all you have to do is make an array of selected cells and add or remove borders in

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

method

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //each cell is refreshed when page is scrolled


    //Matches every cell to see if it is selected or not and adds or removes borders accordinglly
    NSNumber *rowNsNum = [NSNumber numberWithUnsignedInt:indexPath.item];
    if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%@",rowNsNum]]  )
    {
        [cell.layer setBorderColor:[UIColor orangeColor].CGColor];
        cell.layer.borderWidth = 5.0f;


    }
    else
    {
        [cell.layer setBorderColor:[UIColor clearColor].CGColor];
        cell.layer.borderWidth = 0.0f;
    }



    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //Adds cells indexPath to selectedCellsArray and adds border around the cell right away
    NSLog(@"selected");
    UICollectionViewCell*selectedCell = [collectionView cellForItemAtIndexPath:indexPath];


    if (![selectedCellsArray containsObject:[NSString stringWithFormat:@"%d",indexPath.item]] ) {
        [selectedCellsArray addObject:[NSString stringWithFormat:@"%d",indexPath.item]];

        [selectedCell.layer setBorderColor:[UIColor orangeColor].CGColor];
        selectedCell.layer.borderWidth = 5.0f;
        NSLog(@"add");
    }

    NSLog(@"keep track of array:%@", selectedCellsArray);

}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    //Removes cells indexPath from selectedCellsArray and removes border form cell right away
    NSLog(@"deselected");
    UICollectionViewCell*deselectedCell = [collectionView cellForItemAtIndexPath:indexPath];

    if ( [selectedCellsArray containsObject:[NSString stringWithFormat:@"%d",indexPath.item]]  )
    {
        [selectedCellsArray removeObject:[NSString stringWithFormat:@"%d",indexPath.item]];

        [deselectedCell.layer setBorderColor:[UIColor clearColor].CGColor];
        deselectedCell.layer.borderWidth = 0.0f;
        NSLog(@"remove");

    }
  } 
user3296487
  • 326
  • 2
  • 12

0 Answers0