UICollectionView multiple cell types in the same section using Compositional layout

Viewed 627

I have two Type of cell "ProductCell" and "NoImageProductCell". The data is provided by an API so I have no control over the type of product that I will get(with or without image).

How to use Compositional Layout to show both types in the same section with different cell size.

1 Answers

I ended up using NSCollectionLayoutGroup.custom that let you size each item that belong to a group separately.

    let items = self.dataSource.snapshot().itemIdentifiers(inSection: 2)
                let group = NSCollectionLayoutGroup.custom(layoutSize: groupSize) { (env) -> [NSCollectionLayoutGroupCustomItem] in
                var customItems = [NSCollectionLayoutGroupCustomItem]()
                items.forEach { (object) in
                    switch object.imageURL {
                    case .none:
                        //calculate frame and append item
customItems.append(NSCollectionLayoutGroupCustomItem(frame: yourFrame))
                    case .some(_):
                        //calculate frame and append item
customItems.append(NSCollectionLayoutGroupCustomItem(frame: yourFrame))
                    }
                }
                return customItems
            }
Related