添加一个简单的 UIView 作为 UICollectionView 的标题 [英] Add a simple UIView as header of UICollectionView

查看:24
本文介绍了添加一个简单的 UIView 作为 UICollectionView 的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a UICollectionView. I would like to add a header. My header would only be a UILabel. I've :

1) 在 IB 中选择Section Header"作为 Collection View 附件.

1) selected "Section Header" as a Collection View accessory in the IB.

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

2) created a Collection Reusable View in the IB, on the side, declared as collectionViewHeader.

3) 添加了这些行:

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

            return collectionViewHeader;
    }
    return nil;
}

但它们永远不会被调用.

But they are never called.

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

Do I have to create a class just for that label in order to use

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

?

为什么它不像 UITableView 那样简单,您只需拖放任何您想要的标题?!UICollectionView 让事情变得如此复杂...

Why isn't it as simple as the UITableView where you just drag and drop whatever header you want ?! Things are so complicated with UICollectionView...

推荐答案

如下图所示

注册标题视图

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
}

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

Important is that you are supply the flow layout with the header size

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

否则数据源方法不会被调用

Otherwise the data source method will not get called

这篇关于添加一个简单的 UIView 作为 UICollectionView 的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆