UICollectionView: minimumInteritemSpacing change on cell selection

1k Views Asked by At

In my collection view I want to scale the collection view cell that is selected. Along with that I also want to maintain same interItemSpacing between cells before the selection and after the selection, including enlarged cell. But if I just scale the cell by setting cell.transform property scaled cell overlaps on the neighbor cell.Other cells should adjust themselves to maintain the space. How do I solve this ?

i.e,

  cell -50pix- cell -50pix- cell

  cell -50pix- scaled cell -50pix- cell
2

There are 2 best solutions below

1
On BEST ANSWER

By applying a transform, you are just scaling the view up in size. To adjust the size and allow the rest of the UICollectionView to adjust you will need to return a new size in sizeForItemAtIndexPath:

When the item is selected, you should reload that item at that indexPath using:

 [collectionView reloadItemAtIndexPath:selectedIndexPath]

Replace selectedIndexPath with name of your variable storing the selected indexPath.

You don't want to invalidateLayout because you're just changing the appearance of one item.

0
On

I don't know whether this is the best solution,

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        CollectionViewCell *cell = (CollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor redColor];
        return cell;
    }

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

        if ([indexPath isEqual:selectedIndexPath]) {
            return CGSizeMake(175, 175);  // return enlarged size if selected cell
        }
        return CGSizeMake(150, 150);
    }
    -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        selectedIndexPath = indexPath;   // set selected indexPath
        [collectionView performBatchUpdates:^{
                [collectionView.collectionViewLayout invalidateLayout];
            } completion:^(BOOL finished) {
                }];
    }

    - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
        return UIEdgeInsetsMake(0, 0,0, 0);
    }

    - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
        return 20;
    }
    - (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
        return 20;
    }