Search code examples
iosuicollectionviewuicollectionviewcelluicollectionviewlayout

UICollectionViewCell spacing


I have a UICollectionView that fits 3 cells on width (and scrolls vertically). When I change the rotation of the device, the collection view stretches a little bit, and the cells spacing increases a little too. Yet, the left cell snaps to the left margin, the right cell snaps to the right margin and the center cell remains centered.

I'd prefer if there could be a margin on both sides, with equal dimension to the distance between cells, so it'd look less spaced.

I tried calling [collectionView setContentInset:UIEdgeInsetsMake(0, 10, 0, 10)];, but that just added a horizontal scroll to the view, instead of approximating the cells.

How can I add a margin without altering the scrollview size?


Solution

  • I figured it out. I had to add this delegate method:

    - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
      return UIInterfaceOrientationIsPortrait([self interfaceOrientation]) ? UIEdgeInsetsMake(0, 22, 0, 21) : UIEdgeInsetsMake(0, 0, 0, 0);
    }
    

    And refresh the collection view on - willRotateToInterfaceOrientation:duration::

      [[_collection collectionViewLayout] invalidateLayout];
      [_collection reloadData];