ios - 如何使用 UICollectionViewLayout 以编程方式在 UICollectionView 上添加 header

标签 ios iphone cocoa-touch

我的一个 viewcontroller 中有一个 UICollectionView。我的 Collection View 使用 UICollectionViewLayout(自定义)的子类来布置单元格。首先,一旦我在 Storyboard 的下拉菜单中选择 Layout 作为 Custom,选择补充 View 的选项就会消失。

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

- (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;
  }

在我的 viewDidLoad 方法中有

[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];

谁能指出我哪里搞砸了?

最佳答案

您传递的 View 种类不正确。

你注册类(class)的线路:

[self.collectionView registerClass:[UICollectionReusableView class]
  forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
  withReuseIdentifier:@"HeaderView"];

应该是:

[self.collectionView registerClass:[UICollectionReusableView class]
  forSupplementaryViewOfKind: UICollectionElementKindSectionHeader
  withReuseIdentifier:@"HeaderView"];

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

关于ios - 如何使用 UICollectionViewLayout 以编程方式在 UICollectionView 上添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22785507/

相关文章:

iphone - iPhone虚拟键盘添加新按钮?

iphone - iPhone SDK 的文件错误

iphone - 转让应用程序(包括银行业务)的所有权,而不影响当前排名

iphone - 远程唤醒应用程序,比如从蓝牙设备

objective-c - 将多维 NSMutableArray 中的数据提取到更简单的数组中

objective-c - UIButton setImage 未从非触摸操作更新

ios - 快速更新行错误 - 尝试添加行...但更新后有 0 行

iphone - 色度计 RGB iPhone ios 代码

iphone - 如何防止iPhone应用程序在非视网膜设备上运行?

iPhone:UIView 高度为 1 像素