Modern collection view registration with Storyboards?

Can you use modern collection view cell/view registration with custom views designed in a storyboard?

I am familiar with putting a custom cell, or reusable view, inside the collection view of the storyboard, and configuring it with constraints and outlets. Then manually dequeueing the cell/view, and configuring the view.

How do you do this with the new decoupled methods of cell registration and configuration?

For example, if I have the following:

        let headerRegistration = UICollectionView.SupplementaryRegistration

        <HeaderReusableView>(elementKind: "header") { (supplementaryView, _, indexPath) in
            supplementaryView.titleLabel?.text = "foo"
        }

        self.datasource?.supplementaryViewProvider = { (_, _, index) in
            return self.collectionView.dequeueConfiguredReusableSupplementary(using: headerRegistration, for: index)
        }

HeaderReusableView is a UICollectionReusableView that is added to my storyboard, and the titleLabel is added, and hooked up via an outlet. When I run the code, it does not seem to make the connection, and the outlet is nil.

Replies

You have :

elementKind: "header"

Where did you define it ?

Did you try replacing with:

elementKind: "Header"

Or simply UICollectionView.elementKindSectionHeader

There was an interesting discussion on the forum a few months ago, if that may help:

https://developer.apple.com/forums/thread/682570

  • I am using compositional layout. So it is defined like this:

    let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(                 layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),                                                   heightDimension: .estimated(44)),                 elementKind: "header",                 alignment: .top)             section.boundarySupplementaryItems = [sectionHeader]
Add a Comment

Claude31, your answer did put me on the right track. I realized that the real issue is that I don't think storyboards support compositional layouts just yet, and when you put a cell/view in a storyboard, it is somehow tied to the layout. I found that I could get visual design using a nib though, and then this code works:

let headerRegistration = UICollectionView.SupplementaryRegistration<HeaderReusableView>(supplementaryNib: UINib(nibName: "HeaderReusableView", bundle: Bundle(for: HeaderReusableView.classForCoder())), elementKind: "header") { supplementaryView, elementKind, indexPath in

            supplementaryView.titleLabel?.text = self.sections[indexPath.section].rawValue

        }