When I set up a UICollectionReusableView cell in storyboard and try to dequeue a cell of this type, my app crashes with this error message:
Steps I've gone through to add my collection reusable view in storyboard:
- I added a collection reusable view by dragging the item from the panel of objects to my collection view.
- I created a class called EmotionFiltersHeaderView which subclasses UICollectionReusableView that contains a reference to an IBOutlet var for the label I added to the reusable view (also in storyboard).
- I changed the class name of the reusable view in the storyboard to my custom class name, EmotionFiltersHeaderView.
- I added an identifier to the reusable view and called it "emotionFiltersHeaderReusableView".
- I've included the header view in the boundary supplementary items property of the section where I'm adding the header view.
This is my code:
`let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(37.0))
let header = NSCollectionLayoutBoundarySupplementaryItem(
layoutSize: headerSize,
elementKind: UICollectionView.elementKindSectionHeader,
alignment: .topLeading)
section.boundarySupplementaryItems = [header]
emotionFiltersDataSource.supplementaryViewProvider = { collectionView, kind, indexPath in
guard let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: ElementKind.sectionHeader.rawValue,
withReuseIdentifier: "emotionFiltersHeaderReusableView",
for: indexPath
) as? EmotionFiltersHeaderView else {
fatalError("Could not dequeue header view as EmotionFiltersHeaderView")
}
let sectionTitle = Section.allCases[indexPath.section].rawValue
headerView.sectionTitleLabel.text = sectionTitle
return headerView
}
enum ElementKind: String { case sectionHeader = "section-header-element-kind" }`
Assuming the supplementary view has been registered properly, then the only other thing I see is that the element kind strings are mismatched.
In your layout, you are specifying the elementKind as UICollectionView.elementKindSectionHeader (which is the string "UICollectionElementKindSectionHeader").
But when you dequeue the view, you are requesting it be of kind ElementKind.sectionHeader.rawValue ("section-header-element-kind").
I think this might be the cause of the crash.