添加一个简单的UIView作为UICollectionView的头

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

1)在IB中select“部分标题”作为收集视图附件。

2)在IB中创build了一个集合可重用视图,声明为collectionViewHeader

3)添加这些行:

 - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { if (kind == UICollectionElementKindSectionHeader) { return collectionViewHeader; } return nil; } 

但他们从来没有被称为。

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

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

为什么不像UITableView那样简单,只需拖放任何你想要的标题? 事情是如此复杂的UICollectionView

如果不在故事板中设置标题,则必须注册。

在viewDidLoad中:

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

但无论如何,你将不得不inheritanceUICollectionReusableView。

 @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; } 

像下面那样迅速

注册标题视图

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

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 } 

重要的是你提供的头部大小的stream布局

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

否则委托方法将不会被调用

只需将视图添加到UICollectionView并更改insets

 collectionView.addSubview(headerView) collectionView.contentInset.top = 300 headerView.frame = CGRect(x: 0, y: -300, width: collectionView.frame.size.width, height: 300)