2012-10-03 40 views
39

我正在使用UICollectionView來顯示多個相冊的項目。項目顯示正常,但現在我想在第一部分上方顯示標題。UICollectionView標題未顯示

爲此,我將registerNib:forSupplementaryViewOfKind:withReuseIdentifier:添加到了我的init方法中。像這樣:

[self.collectionView registerNib:[UINib nibWithNibName:@"AlbumHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kAlbumHeaderIdentifier]; 

(該AlbumHeader筆尖包含類AlbumHeader,這是UICollectionView一個子類的視圖)

之後,我實現collectionView:viewForSupplementaryElementOfKind:atIndexPath方法:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { 
    return [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kAlbumHeaderIdentifier forIndexPath:indexPath]; 
} 

現在它應該嘗試加載標題視圖,我想。但它不會,補充視圖的方法不會被調用。

我錯過了什麼?卡住了幾個小時,多次閱讀了關於UICollectionView的文檔,但似乎沒有任何幫助。有什麼想法嗎?

回答

106

尋找yuf被問及方法後,我讀取默認情況下,頁眉/頁腳的大小是0,0。如果大小爲0,則頁眉/頁腳不會顯示。

您可以使用屬性設置大小:

flowLayout.headerReferenceSize = CGSizeMake(0, 100); 

然後所有的標題將具有相同的大小。如果每個部分必須不同,則可以實施以下方法,該方法是UICollectionViewDelegateFlowLayout協議的一部分。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section { 
    if (section == albumSection) { 
     return CGSizeMake(0, 100); 
    } 

    return CGSizeZero; 
} 

注意,在垂直滾動它使用返回height和集合視圖的整個寬度,水平滾動它使用返回width和集合視圖的整個高度。

+4

對於任何人仍然遇到這個問題,爲了讓我做這個工作,我還必須給'collectionview.footerReferenceSize'的大小。不知道該請求是否是iOS 7特有的... –

+1

這是一個難以置信的提示。非常感謝,Guido! – Fattie

+1

享受賞金! :) – Fattie

2

你有沒有實現:

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 

有一噸的方法來實現只是爲了一兩件事的工作......我也學習。告訴我它是否有效。

編輯:對不起錯誤的方法。這是我認爲的子類。我在談論的一個是在UICollectionViewLayout(佈局對象,你繼承,如果你的佈局支持的補充意見):

- layoutAttributesForSupplementaryViewOfKind:atIndexPath: 

在這裏看到:https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UICollectionViewLayout_class/Reference/Reference.html#//apple_ref/occ/cl/UICollectionViewLayout

+0

該方法似乎不是任何代表的一部分? –

+0

@GuidoH是否使用了FlowLayout或您的自定義佈局?這個答案是指自定義佈局。 – Juguang

+0

我確實使用了流佈局。被接受的答案解決了這一切,並且也是合理的。 =) –