UICollectionView with section headers like a UITableView UICollectionView with section headers like a UITableView ios ios

UICollectionView with section headers like a UITableView


  1. Enable the section header/footer view in Storyboard.

  2. Implement collectionView:viewForSupplementaryElementOfKind method.

see This Link


Adding section headers in a collection view works for me with the following set up:

  1. add a xib file to define the header view content. The xib file contains only one cell type definition. In my case, the header view has a custom type (ImageCollectionViewHeaderCell) which derives from UICollectionViewCell. I think it is required but I'm not sure. The cell identifier is also set to predefined string (e.g.) "ImageCollectionViewHeaderCellId"

  2. add header and implementation files for the custom type. It is convenient to have a method to get its UINib object (a kind of proxy for the xib file created at step 1)

    @implementation ImageCollectionViewHeaderCell+ (UINib*) nib{  return [UINib nibWithNibName:@"nameOfXibFileCreatedAtStep1" bundle:nil];}@end
  3. in the collection view controller (which, in my case, is also the dataSource and delegate of the UICollectionView), in the viewDidLoad method, add the registration for the supplementary element type

    - (void) viewDidLoad{   [_collectionView registerNib:[ImageCollectionViewHeaderCell nib] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ImageCollectionViewHeaderCellId"];}
  4. in the collection view controller, add the methods to return a non null header height and the header view instances

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{  return CGSizeMake(0., 30.);}- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{  NSAssert([kind isEqualToString:UICollectionElementKindSectionHeader], @"Unexpected supplementary element kind");  UICollectionReusableView* cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind                                                              withReuseIdentifier:ImageCollectionViewHeaderCellIdentifier                                                                     forIndexPath:indexPath];  NSAssert([cell isKindOfClass:[ImageCollectionViewHeaderCell class]], @"Unexpected class for header cell");  ImageCollectionViewHeaderCell* header_view = (ImageCollectionViewHeaderCell*) cell;  // custom content  return cell;}


matomo