UICollectionView和自定义UICollectionReusableView不起作用

Rom*_*ski 10 xib ios uicollectionview uicollectionreusableview

我正在尝试UICollectionReusableViewUICollectionView标题中使用自定义(具有自己的类和XIB).但是在获取标题后的数据后,我什么都没有.

我的步骤:

  1. viewDidLoad中注册类:

     [self.collectionView registerClass:[CollectionViewHeader class] 
      forSupplementaryViewOfKind: UICollectionElementKindSectionHeader 
      withReuseIdentifier:@"HeaderView"];
    
    Run Code Online (Sandbox Code Playgroud)
  2. 试图显示:

    - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    {
    UICollectionReusableView *reusableView = nil;
    
    if (kind == UICollectionElementKindSectionHeader) {
        CollectionViewHeader *collectionHeader = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
    
        NSInteger section = [indexPath section];
        id <NSFetchedResultsSectionInfo> sectionInfo = [fetchRecipes sections][section];
        collectionHeader.headerLabel.text = @"bla-bla-bla";
    
        reusableView = collectionHeader;
    }
    
    return reusableView;
    }
    
    Run Code Online (Sandbox Code Playgroud)

谁能告诉我什么是错的?)感谢您的任何建议

Ani*_*ese 12

我想你正在为xib添加标签.所以你需要registerNib:用于头文件而不是registerClass:


and*_*yjr 10

  1. 在viewDidLoad部分中注册标题nib/xib.

    [self.collectionView registerNib:  [UINib nibWithNibName:@"headerCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"headerCell"]; 
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建自定义补充视图单元格.

    - (headerCollectionViewCell *)collectionView:(UICollectionView *)collectionViews viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
    {
        UICollectionReusableView *reusableView = nil;
    
        if (kind == UICollectionElementKindSectionHeader) {
    
            UINib *nib = [UINib nibWithNibName:@"headerCollectionViewCell" bundle:nil];
    
            [collectionViews registerNib:nib forCellWithReuseIdentifier:@"headerCell"];
    
            headerCollectionViewCell *collectionHeader = [collectionViews dequeueReusableCellWithReuseIdentifier:@"headerCell" forIndexPath:indexPath];
            collectionHeader.titleLabel.text = @"What";
    
            reusableView = collectionHeader;
       }
    
       return reusableView;
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 你正在使用`registerNib:forCellWithReuseIdentifier:`.你应该使用`registerNib:forSupplementaryViewOfKind:withReuseIdentifier:` (7认同)