1

我正在嘗試爲我的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實施,應用程序工作沒有任何問題。

已將頭部鏈接到故事板中的類。 可能是什麼問題?

在此先感謝。

回答

1

得到了issue.It到了的CollectionView正在採取的可重複使用的視圖頁腳,而不是頭的原因所致。將它更改爲標題,現在應用運行良好。感謝所有幫助。

0

檢查您是否註冊了forSupplementaryViewOfKind

如果沒有則嘗試在viewDidLoad中註冊您的supplementaryView

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

當我刪除referenceSizeForHeaderInSection實現時,該應用可以正常工作。我不這是註冊頭的問題。 – Vyshakh

+0

你試過了上面的代碼嗎? @Vyshakh –

+1

欲瞭解更多的澄清閱讀此https://stackoverflow.com/a/29656061/8432814回答 –

0

確保您的重用標識符相同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