UICollectionView标题不显示

问题描述:

我正在开发一个使用 UICollectionView 显示多个相册的项目。

I'm working on a project that uses an UICollectionView to show several albums. The items show fine, but now I want to show an header above the first section.

为了做到这一点,我添加了 registerNib:forSupplementaryViewOfKind: withReuseIdentifier:到我的init方法。像这样:

To do this, I added the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: to my init method. Like this:

[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];
}

现在它应该尝试加载头视图。但是没有,补充视图的方法不会被调用。

Now it should try to load the header view, I suppose. But it doesn't, the method for the supplementary view doesn't get called.

我缺少什么? Stuck几个小时,已经阅读了 UICollectionView 的文档很多次,但没有什么似乎有帮助。任何想法?

What am I missing? Stuck for hours, have read the documentation on UICollectionViews many times, but nothing seems to help. Any thoughts?

在寻找方法yuf询问,我读到默认情况下,页眉/ ,0。如果大小为0,则不会显示页眉/页脚。

After looking for the method yuf asked about, I read that by default the size of headers/footers are 0,0. If the size is 0, the header/footer won't display.

您可以使用属性设置大小:

You can set the size with a property:

flowLayout.headerReferenceSize = CGSizeMake(0, 100);

那么所有的头都会有相同的大小。如果对于每个部分它必须不同,您可以实现以下方法,它是 UICollectionViewDelegateFlowLayout 协议的一部分。

Then all the headers will have the same size. If it has to be different for each section, you can implement the following method, which is part of the UICollectionViewDelegateFlowLayout protocol.

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

    return CGSizeZero;
}

请注意,在垂直滚动中,它使用返回的 和集合视图的全宽,在水平滚动中,它使用返回 width 和集合视图的完整高度。

Note that in vertical scrolling it uses the returned height and the full width of the collection view, in horizontal scrolling it uses the return width and the full height of the collection view.