我试图为我的部分提供不同的背景颜色/图像,但发现很难在 createCompositionalLayout() 中设置两个不同的背景视图。
下面是两个背景视图组件和部分。在布局创建方法中有各种注册类/笔尖的示例,但这只是为所有部分创建一个背景视图。
在 createCompositionalLayout() 中有一个用于返回 NSCollectionLayoutSection (部分)的开关,但要为每个部分返回已注册的背景视图布局是我的障碍。
func createCompositionalLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { sectionIndex, layoutEnvironment in
guard let sectionKind = SectionBack(rawValue: sectionIndex) else { return nil }
let section = self.sections[sectionIndex]
switch section.type {
case "mediumTable":
return self.createMediumTableSection(using: section)
case "smallTable":
return self.createSmallTableSection(using: section)
default:
return self.createFeaturedSection()
}
}
return layout
}
**Red backgroundview**
let backgroundItem = NSCollectionLayoutDecorationItem.background(elementKind: "background")
let backgroundInset: CGFloat = 8
backgroundItem.contentInsets = NSDirectionalEdgeInsets(top: backgroundInset, leading:
backgroundInset, bottom: backgroundInset, trailing: backgroundInset)
layoutSection.decorationItems = [backgroundItem]
let layout = UICollectionViewCompositionalLayout(section: layoutSection)
layout.register(RedBackgroundSupplementaryView.self, forDecorationViewOfKind:
"background")
func createMediumTableSection(using section: Section) -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(0.33))
let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)
layoutItem.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)
let layoutGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.93), heightDimension: .fractionalWidth(0.55))
let layoutGroup = NSCollectionLayoutGroup.vertical(layoutSize: layoutGroupSize, subitems: [layoutItem])
let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
layoutSection.orthogonalScrollingBehavior = .groupPagingCentered
let layoutSectionHeader = createSectionHeader()
layoutSection.boundarySupplementaryItems = [layoutSectionHeader]
return layoutSection
}
func createSmallTableSection(using section: Section) -> NSCollectionLayoutSection {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(0.2))
let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)
layoutItem.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 0)
let layoutGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.93), heightDimension: .estimated(200))
let layoutGroup = NSCollectionLayoutGroup.vertical(layoutSize: layoutGroupSize, subitems: [layoutItem])
let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
let layoutSectionHeader = createSectionHeader()
layoutSection.boundarySupplementaryItems = [layoutSectionHeader]
return layoutSection
}