CollectionView方法'referenceSizeForHeaderInSection'抛出异常

问题描述:

我正在尝试为我的collectionView创建具有动态高度的标头。但是,当我实施“referenceSizeForHeaderInSection”,应用程序崩溃,但以下情况除外:CollectionView方法'referenceSizeForHeaderInSection'抛出异常

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' 

下面是对的CollectionView头的代码:因为我还没有添加任何

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 FeedHeader: UICollectionReusableView 
{ 

} 

当我删除referenceSizeForHeaderInSection实施,应用程序工作没有任何问题。

已将头部链接到故事板中的类。 可能是什么问题?

在此先感谢。

得到了issue.It到了的CollectionView正在采取的可重复使用的视图页脚,而不是头的原因所致。将它更改为标题,现在应用运行良好。感谢所有帮助。

检查您是否注册了forSupplementaryViewOfKind

如果没有则尝试在viewDidLoad中注册您的supplementaryView

collectionView.register(nibName, forSupplementaryViewOfKind: "String", withReuseIdentifier: "Identifier") 
+0

当我删除referenceSizeForHeaderInSection实现时,该应用可以正常工作。我不这是注册头的问题。 – Vyshakh

+0

你试过了上面的代码吗? @Vyshakh –

+1

欲了解更多的澄清阅读此https://stackoverflow.com/a/29656061/8432814回答 –

确保您的重用标识符相同FeedHeader

检查以下内容:

  1. 在选择你的头图Stoaryboard

identifier

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 

    let headerView: TitleHeaderCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TitleHeaderCollectionReusableView", for: indexPath as IndexPath) as! TitleHeaderCollectionReusableView 
return headerView 
} 

也实现了您的首选高度

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { 

      return CGSize(width: collectionObj.frame.size.width, height: 50) 
    } 
+0

我已经实施了所有提到的建议。它仍然给出同样的错误。但是,如果我删除referenceSizeForHeaderInSection,该应用程序工作正常。 – Vyshakh