2012-10-03 43 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

我确实使用了流布局。被接受的答案解决了这一切,并且也是合理的。 =) –