How to set dynamic spacing of UICollectionViewCell

I had a problem setting the spacing between cells in my collection view. Everything looks good on the iPhone 5, but when I launch it on 6 and 6, the distance between the cells increases dramatically. I set the minimum distance to 10, but that doesn't seem to help. The first image is what I am trying to achieve on all devices. The following snapshots are what I actually get:

iPhone 5

iPhone 6

iPhone 6 plus

Here is an image of my settings in IB:

IB Settings

+5
source share
1 answer

For your question, it looks like you wanted to set minimumInteritemSpacing (minimum spacing between items on the same line).

In any case, the minimum interval is the smallest interval you accept, not the exact interval you want. Space 100 remains valid as it is greater than at least 10.

The real problem is the size of the cell that you fixed at 150x200. If you want your cells to adjust their width, you will need to calculate the layout of the itemSize stream depending on the width of the view.

  • If all your cells are the same size , you can set the itemSize layout itemSize :

     #define kCellsPerRow 2 UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)self.collectionView.collectionViewLayout; CGFloat availableWidthForCells = CGRectGetWidth(self.collectionView.frame) - flowLayout.sectionInset.left - flowLayout.sectionInset.right - flowLayout.minimumInteritemSpacing * (kCellsPerRow - 1); CGFloat cellWidth = availableWidthForCells / kCellsPerRow; flowLayout.itemSize = CGSizeMake(cellWidth, flowLayout.itemSize.height); 
  • If you need to calculate the sizes of each cell , you can do this in the delegate collectionView:layout:sizeForItemAtIndexPath:

Recalculate element size when changing device orientation and updating layout:

  • Redraw the layout without animation:

    [self.collectionView.collectionViewLayout invalidateLayout]

  • Animation of layout changes:

    [self.collectionView performBatchUpdates:nil completion:nil]

+3
source

Source: https://habr.com/ru/post/1206064/


All Articles