0

I have a UICollectionView with the following layout:

private func createCollectionViewLayout() -> UICollectionViewLayout {

    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.49), heightDimension: .estimated(150))

    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    //item.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: NSCollectionLayoutSpacing.flexible(2), top: NSCollectionLayoutSpacing.flexible(2), trailing: NSCollectionLayoutSpacing.flexible(2), bottom: NSCollectionLayoutSpacing.flexible(2))
    
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(1)),
                                                   subitems: [item])
    group.interItemSpacing = NSCollectionLayoutSpacing.flexible(0)
    group.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: NSCollectionLayoutSpacing.flexible(5), top: NSCollectionLayoutSpacing.flexible(5), trailing: NSCollectionLayoutSpacing.flexible(5), bottom: NSCollectionLayoutSpacing.flexible(5))
    
    let section = NSCollectionLayoutSection(group: group)
    
    return UICollectionViewCompositionalLayout(section: section)
}

It works pretty well except that it doesn't fit cells together vertically. i.e. in the image below, I want the 'Spaghetti Carbonara' cell to come directly below the 'Cuban Ropa Vieja' cell. Any idea how I can achieve this?

enter image description here

  • You probably do NOT want to use `UICollectionViewCompositionalLayout` ... take a look at this article: [UICollectionView Custom Layout Tutorial: Pinterest](https://www.kodeco.com/4829472-uicollectionview-custom-layout-tutorial-pinterest) – DonMag Aug 10 '23 at 12:44
  • @DonMag you're right, that's what I needed. A bit harder to implement than I was anticipating but I did get it working. Thank you! – Moses Harding Aug 11 '23 at 21:01

1 Answers1

-1

At DonMag's suggestion, I instead implemented a custom layout using the below tutorial: https://www.kodeco.com/4829472-uicollectionview-custom-layout-tutorial-pinterest

I'll note that the tutorial implemented its collectionview with the interface builder and I implemented mine programmatically, so I had to make sure to initialize it at the right time (i.e. after views had fully loaded).