How to change background color of a whole section in UICollectionView?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)