Search code examples
iosswiftuicollectionviewuicollectionviewcelluicollectionviewlayout

Prioritize spacing over size for UICollectionViewCell


I have a UICollectionView for which I want 3 cells in each row. I want to have a fixed spacing between each cell, with the size of the cell dynamically adjusting.

Yes, I am able to set min cell spacing. However I want this spacing to be fixed. How can I set the spacing between cells to be constant while the cells size adjust?


Solution

  • Here is how I solved it:

    extension ViewController: UICollectionViewDelegateFlowLayout {
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            //Calculate cell width
            let spacingTotal = CGFloat((cellSpacing * 2) + (marginSpacing * 2))
            let screenWidth = UIScreen.main.bounds.width
            let cellWidth = (screenWidth - spacingTotal) / 3.0
    
            //Maintain ratio for cell height
            let widthToHeighRatio = CGFloat(102 / 94)
            let cellHeight = cellWidth * widthToHeighRatio
    
            return CGSize(width: cellWidth, height: cellHeight)
        }
    }
    

    Where cellSpacing is the value of your minimum cell spacing. And margingSpacing is the total value of your right and left margins for the collectionView.

    Also note I'm maintaining a ratio for the cell size; the designs I'm working with display a 102 x 94 cell, so I'm maintaining that ratio for every screen size.

    Here's how it looks on an iPhone SE and iPhone X:

    enter image description here enter image description here