CollectionView方法'referenceSizeForHeaderInSection'抛出异常

时间:2017-09-14 04:49:15

标签: ios swift3 uicollectionview uicollectionreusableview uicollectionviewdelegateflowlayout

我正在尝试使用动态高度为我的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实现时,该应用程序可以正常运行。

在故事板中也将标题链接到了类。 可能是什么问题?

提前致谢。

3 个答案:

答案 0 :(得分:1)

遇到了问题。这是因为collectionView将可重用视图作为页脚而不是标题。将其更改为标题,现在应用程序运行正常。感谢所有人的帮助。

答案 1 :(得分:0)

检查您是否已注册 forSupplementaryViewOfKind

如果没有,请尝试在 viewDidLoad

中注册您的supplementView
collectionView.register(nibName, forSupplementaryViewOfKind: "String", withReuseIdentifier: "Identifier")

答案 2 :(得分:0)

确保您的重用标识符与FeedHeader

相同

检查以下内容:

  1. 在Stoaryboard中选择标题视图
  2. 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)
        }
    
相关问题