3

I have a collection view powered by compositional layout + diffable data source. It uses three supplementary boundary items: a header, footer, and "leading-header".

App Layout Example

The problem is: fractional size for leading headers is based on the whole container, not the section. So I can't simply set the header's 'fractional height = 1'. Instead, I need to calculate the section size, and set the height of the leading-header to it using 'absolute value'. But how can I get the size of the section?

func createFoodSection(using section: FoodCategory, sectionIndex: Int) -> NSCollectionLayoutSection {
      let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(75),
                                            heightDimension: .fractionalHeight(1.0))
      let item = NSCollectionLayoutItem(layoutSize: itemSize)
      
      let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                             heightDimension: .absolute(39))
      let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
                                                     subitems: [item])
      
      let leftSize = NSCollectionLayoutSize(widthDimension: .absolute(5.0),
                                            heightDimension: .absolute(120.0))
      let leftSection = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: leftSize,
                                                             elementKind: "leadingKind",
                                                             alignment: .leading)
      
      let topSectionHeader = createSectionHeader()
      let layoutSection = NSCollectionLayoutSection(group: group)
      layoutSection.boundarySupplementaryItems = [topSectionHeader, leftSection]
      
      return layoutSection
   }

Group height in the section is fixed at .absolute(39). So I should be able to calculate height if I know number of groups in a section.

Bonus points! the sections are expand-collapsible. Meaning the height of the leading-header needs to change on expand-collapse of its section.

theogood
  • 85
  • 1
  • 1
  • 7
  • This is not possible using compositional layout. You would need to write your own layout class from scratch, and even then I don't know how you'd do it. – matt Nov 01 '20 at 12:54
  • I'm experimenting with using dataSource.supplementaryViewProvider to set header height. The dataSource has knowledge of contents of the section, so maybe I can calculate section height based on contents (# of items in section). Override the height set in the Compositional Layout. Sort of hacky, but maybe works? – theogood Nov 01 '20 at 13:43

0 Answers0