iosswift3uicollectionviewuicollectionreusableviewuicollectionviewdelegateflowlayout

CollectionView method 'referenceSizeForHeaderInSection' throws exception


I am trying to create headers for my collectionView with dynamic height. But when I implement "referenceSizeForHeaderInSection", the app crashes with the following exception:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindSectionHeader with identifier FeedHeader - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

Below is the code for the collectionView header:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return feedArray.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: collectionView.frame.size.width - 20 , height: 70)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "FeedHeader", for: indexPath) as! FeedHeader

    return header
}

FeedHeader class is empty as I haven't added any labels to the header yet:

class FeedHeader: UICollectionReusableView
{

}

When I remove referenceSizeForHeaderInSection implementation, the app works without any issues.

Have linked the header to the class as well in the storyboard. What might be the problem?

Thanks in advance.


Solution

  • Got the issue.It was due to the reason that the collectionView was taking the reusable view as footer instead of header. Changed it to header and now the app runs fine. Thanks for the help all.