如何使用UICollectionViewLayout以编程方式在UICollectionView上添加标头

Man*_*uja 23 iphone cocoa-touch ios

我有一个UICollectionView在我的viewcontroller.我的集合视图使用UICollectionViewLayout(custom)的子类来布局单元格.首先,一旦我在Storyboard的下拉列表中选择Layout as Custom,选择补充视图的选项就会消失.

我尝试以编程方式执行此操作,如下所示,但没有调用任何委托方法.

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

        UICollectionReusableView *reusableview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];

        if (reusableview==nil) {
            reusableview=[[UICollectionReusableView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
          }

        UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        label.text=[NSString stringWithFormat:@"Recipe Group #%li", indexPath.section + 1];
        [reusableview addSubview:label];
        return reusableview;
      }
    return nil;
  }

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGSize headerSize = CGSizeMake(320, 44);
    return headerSize;
  }
Run Code Online (Sandbox Code Playgroud)

在我的viewDidLoad方法中我有

[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
Run Code Online (Sandbox Code Playgroud)

任何人都可以指出我搞砸了哪里?

dan*_*zlo 18

你传递的是错误的视图类型.

您注册课程的行:

[self.collectionView registerClass:[UICollectionReusableView class]
  forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
  withReuseIdentifier:@"HeaderView"];
Run Code Online (Sandbox Code Playgroud)

应该:

[self.collectionView registerClass:[UICollectionReusableView class]
  forSupplementaryViewOfKind: UICollectionElementKindSectionHeader
  withReuseIdentifier:@"HeaderView"];
Run Code Online (Sandbox Code Playgroud)

编辑:看起来您的代码全部使用sectionFooter.您是否尝试以编程方式添加页眉或页脚?


Man*_*uja 9

发现问题,我没有在此UICollectionLayoutView方法中返回标头的属性:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect; // return an array layout attributes instances for all the views in the given rect
Run Code Online (Sandbox Code Playgroud)


Suk*_*shj 8

检查您是否在UICollectionViewFlowLayout中为标题指定了引用大小

[flowLayout setHeaderReferenceSize:CGSizeMake(320, 50)];
Run Code Online (Sandbox Code Playgroud)

并为页脚

[flowLayout setFooterReferenceSize:CGSizeMake(320, 50)];
Run Code Online (Sandbox Code Playgroud)

  • 这些方法仅适用于UICollectionViewFlowLayout,而不适用于UICollectionViewLayout. (6认同)