41

我有一个UICollectionView. 我想添加一个标题。我的标题只会是一个UILabel. 我有 :

1) 在 IB 中选择“Section Header”作为 Collection View 附件。

2)在 IB 中创建了一个 Collection Reusable View,在侧面,声明为collectionViewHeader.

3)添加了这些行:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {

            return collectionViewHeader;
    }
    return nil;
}

但他们永远不会被调用。

我是否必须为该标签创建一个类才能使用

[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

?

为什么它不像UITableView你只需拖放任何你想要的标题那么简单?!事情太复杂了UICollectionView……

4

3 回答 3

57

像下面这样迅速

注册标题视图

collectionView.register(HeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerView")

UICollectionViewDataSource

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView", forIndexPath: indexPath)

    headerView.frame.size.height = 100

    return headerView
}

重要的是您要为流布局提供标题大小

flowLayout.headerReferenceSize = CGSize(width: self.collectionView.frame.size.width, height: 100)

否则不会调用数据源方法

于 2016-09-08T18:39:52.963 回答
24

如果您没有在情节提要中设置标题视图,则必须注册 nib。

viewDidLoad 中的示例:

- (void)viewDidLoad
{
    [self.collectionView registerClass:NSStringFromClass([YourOwnSubClass class]) forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderViewIdentifier"];
}

无论如何,你也可以继承 UICollectionReusableView。

@interface YourOwnSubClass : UICollectionReusableView

然后在您的课程示例中调用委托:

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{

    YourOwnSubClass *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                         UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];    
    [self updateSectionHeader:headerView forIndexPath:indexPath];

    return headerView;
}

- (void)updateSectionHeader:(UICollectionReusableView *)header forIndexPath:(NSIndexPath *)indexPath
{
    NSString *text = [NSString stringWithFormat:@"header #%i", indexPath.row];
    header.label.text = text;
}

并且不要忘记在集合视图或流布局中设置标题大小,以便标题视图可见。

于 2014-02-12T15:40:21.320 回答
3

如果您忘记在您的 XIB 文件中启用附件,以上都不起作用,不要忘记激活您想要的部分!

在此处输入图像描述

于 2020-10-22T18:50:05.563 回答