UICollectionView with section headers like a UITableView

余生长醉 提交于 2019-11-30 02:48:47
david72
  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;
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!