iosswiftuicollectionviewuikituicollectionviewflowlayout

how to implement a uicollectionview that has multiple sections and subsections?


The uicollectionview has n sections (say 1,2,3) that has m subsections (say 1.1,1.2 etc) which further branches into inner subsections (1.1.1, 1.1.2 etc) which finally has X no. of rows in it.

Like the layout in this picture


Solution

  • I've implemented this using UICollectionViewCompositionalLayout. Used the UICollectionViewCompositionalLayout { [self] (sectionNumber, environment) -> NSCollectionLayoutSection? in .... } closure to setup the layout items and group them vertically and horizontally to form the layout for the entire section.

    For reference -

    To create an individual item (H: 50, W: 50) -

    let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .absolute(50), heightDimension: .absolute(50)))
    

    To create groups (Horizontal) -

    let group = NSCollectionLayoutGroup.horizontal(layoutSize:
                                                                        NSCollectionLayoutSize(widthDimension:
                                                                                .absolute(item.layoutSize.widthDimension.dimension * CGFloat((data.count))),
                                                                                               heightDimension:  .estimated(50)), subitem: item, count: (data.count))
    

    Group - vertical

     let subGroup = NSCollectionLayoutGroup.vertical(layoutSize:
                                                                NSCollectionLayoutSize(widthDimension:
                                                                        .absolute(CGFloat(width)),
                                                                                       heightDimension:
                                                                        .absolute(heightForIndividualItem * CGFloat(data.count))),
                                                            subitems: group)