swift – iOS Error: couldn’t dequeue a view of sort: header with identifier headerReuseIdentifier

Spread the love

I am studying compositional layouts and I am unable to set the header for a bit, that is my complete code

import UIKit

class ViewController: UIViewController {
    personal let collectionView: UICollectionView = {
        let view = UICollectionView(body: .zero, collectionViewLayout: ViewController.createLayout())
        view.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        view.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerReuseIdentifier")
        return view
    override func viewDidLoad() {
        collectionView.dataSource = self
        collectionView.delegate = self
    override func viewDidLayoutSubviews() {
        collectionView.body = view.bounds
    static func createLayout() -> UICollectionViewCompositionalLayout {
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5),
                                              heightDimension: .fractionalHeight(1.0))
        let merchandise = NSCollectionLayoutItem(layoutSize: itemSize)
        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                               heightDimension: .fractionalWidth(0.5))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
        let part = NSCollectionLayoutSection(group: group)
        let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(44))
        let headerElement = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerSize, elementKind: "header", alignment: .high)
        part.boundarySupplementaryItems = [headerElement]
        let structure = UICollectionViewCompositionalLayout(part: part)
        return structure

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind sort: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: sort, withReuseIdentifier: "headerReuseIdentifier", for: indexPath)
        return headerView

I’ve registered for header on the time of declaring collectionView, I’ve carried out all of the protocols neededs so far as I am conscious.

Leave a Reply

Your email address will not be published. Required fields are marked *