First, make a UICollectionReusableView to be your background view. I’ve simply set mine to be red.
class SectionBackgroundDecorationView: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .red
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Then, in YourCollectionViewController:
static let background = "background-element-kind"
init() {
super.init(collectionViewLayout: YourCollectionViewController.createLayout())
}
static func createLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int,
layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
// Use sectionIndex to control the layout in each section
if sectionIndex == 0 {
// Customise itemSize, item, groupSize, group to be whatever you want
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
heightDimension: .fractionalHeight(1))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
heightDimension: .absolute(170))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
// Create a sectionBackground
let sectionBackground = NSCollectionLayoutDecorationItem.background(
elementKind: background)
section.decorationItems = [sectionBackground]
return section
} else {
// Your layout for other sections, etc
// You don't have to set a background for other sections if you don't want to
}
}
layout.register(SectionBackgroundDecorationView.self, forDecorationViewOfKind: background)
return layout
}
These links to documentation helped me:
- https://developer.apple.com/documentation/uikit/nscollectionlayoutdecorationitem
- https://developer.apple.com/documentation/uikit/uicollectionviewcompositionallayoutsectionprovider