I'm making a custom section to use in a UICollectionViewCompositionalLayout
. It's supposed to look similar to a UITableViewStyle.grouped
where there's a background behind the cells and a header that's above the background.
The issue I'm running into is by default the NSCollectionLayoutDecorationItem.background
matches size of the section, and the NSCollectionLayoutBoundarySupplementaryItem
for the header extends the bounds of the section causing the background to go behind the header.
If I set header.extendsBoundary = false
, the header is positioned in front of the first cell in the section.
So what I've been doing is setting a top content inset on the background to be equal to the estimated height of the header.
background.contentInsets.top = estimatedHeaderHeight
The issue is that the header height wont always match the estimated height like when the user increases their text size or the test is long enough to wrap. That causes the header height to not match the inset, the header appears to overlay the background.
Any suggestions for getting the desired appearance?
Here's the code I'm using to make the section layout currently.
func groupedSectionLayout(withHeader hasHeader: Bool, environment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1.0),
heightDimension: .estimated(NotificationSettingSwitchCell.estimatedHeight)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let group = NSCollectionLayoutGroup.vertical(layoutSize: itemSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
let background = NSCollectionLayoutDecorationItem
.background(elementKind: ListCollectionBackgroundView.kind.rawValue)
if hasHeader {
let headerHeight = CollectionExtraSmallHeader.estimatedHeight
background.contentInsets.top = headerHeight
let headerSize = NSCollectionLayoutSize(
widthDimension: .fractionalWidth(1),
heightDimension: .estimated(headerHeight)
)
let header = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerSize,
elementKind: CollectionExtraSmallHeaderModel.kind.rawValue,
alignment: .top
)
section.boundarySupplementaryItems = [header]
}
section.decorationItems = [background]
return section
}