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

查看:1448
本文介绍了添加一个简单的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)选择Section Header作为IB中的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...

推荐答案

在swift中下面

注册标题视图

collectionView.registerClass(HeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerView")

In UICollectionViewDelegate

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.width, height: 100)

否则委托方法不会被调用

Otherwise the delegate method will not get called

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

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