2

I want to add a header in Collection View but it gives me the following error.

the view returned from -collectionView:viewForSupplementaryElementOfKind:atIndexPath: was not retrieved by calling -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: for element kind 'CellSeparator' at index path <NSIndexPath: 0xa61e656424039d6a> {length = 2, path = 0 - 1}; supplementary view: <UICollectionReusableView: 0x141e9b380; frame = (0 0; 0 0); layer = <CALayer: 0x6000017c7120>>

extension UICollectionView {
    func registerHeader<T: UICollectionReusableView>(_ header: T.Type) {
        register(nibFromClass(header), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: header.nameOfClass)
    }
}

override func viewDidLoad() {
      super.viewDidLoad()
      collectionView.registerHeader(ThreadsHeaderCell.self)
 }

 override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let collectionViewHeaderFooterReuseIdentifier = "ThreadsHeaderCell"
        if kind == UICollectionView.elementKindSectionHeader {
            let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: collectionViewHeaderFooterReuseIdentifier, for: indexPath) as! ThreadsHeaderCell
         sectionHeader.titleLabel.text = "Test"
         return sectionHeader
        } else { // No footer in this case but can add option for that
            return UICollectionReusableView()
        }
    }

extension ChannelListViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return .init(width: collectionView.frame.width, height: 48)
    }
}

mioeprers
  • 21
  • 2
  • `withReuseIdentifier: header.nameOfClass` vs `let collectionViewHeaderFooterReuseIdentifier = "ThreadsHeaderCell"`, are they the same? It seems that one might be `CellSeparator`, and the other might be `ThreadsHeaderCell`? – Larme Mar 07 '23 at 13:45
  • @mioeprers did you manage to get this working? Any progress debugging the root cause of this? – Frederik Hoeft Jun 19 '23 at 11:13

0 Answers0