5

I'm trying to add a custom view to the header section of my UICollectionView. I have the xib file interface builder but I don't use storyboard. I have checked the Section Header in Interface Builder but doesn't appear any UICollectionReusableView, what can I do?

superarts.org
  • 7,009
  • 1
  • 58
  • 44
Piero
  • 9,173
  • 18
  • 90
  • 160

1 Answers1

12

The easiest solution is to do is programatically (and keep your HeaderReusableView in another XIB file):

[self.collectionView registerNib:[UINib nibWithNibName:@"ItemHeaderView" bundle:nil]
          forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                 withReuseIdentifier:kItemSectionHeaderViewID];

Then:

- (CGSize) collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(60.0f, 30.0f);// width is ignored
}

And of course:

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

    NSString *productId = nil; ///

    ItemHeaderView *view = nil;

    view = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                       withReuseIdentifier:kItemSectionHeaderViewID
                                              forIndexPath:indexPath];

    view.titleLabel.text = productId;

    view.backgroundColor = [UIColor yellowColor];

    return view;
}
mdziadkowiec
  • 1,531
  • 13
  • 11
  • I was using xib. you solution worked for me. Initially I was trying resister NIB `[self.selectionCollectionView registerNib:[UINib nibWithNibName:@"FlootThumbnailCollectionReusableView" bundle:nil] forCellWithReuseIdentifier:@"HeaderView"];` than I changed to `[self.selectionCollectionView registerNib:[UINib nibWithNibName:@"FlootThumbnailCollectionReusableView" bundle:nil] forCellWithReuseIdentifier:@"HeaderView"]` – Anil Gupta Feb 03 '17 at 11:03