美文网首页iOS开发
iOS中UICollectionView 使用xib自定义头部遇

iOS中UICollectionView 使用xib自定义头部遇

作者: Liebling_zn | 来源:发表于2018-12-08 09:45 被阅读263次

由于之前写的时候没有使用Markdown编辑, 所以现在没法更新之前的文章,现在重新弄一份。
首页得说下UICollectionView的使用还是挺广泛的,下面我就针对我项目中遇到的问题和大家说下。我使用UICollectionView需要自定义一个头部的View,
1、创建自定义Header类
*创建一个自定义类,继承自:UICollectionReusableView(我勾选了创建xib布局)
*在xib中定义布局
2、注册Header
我使用的是xib,所以注册如下:

static NSString * const reuseIdentifierHeader = @"HomeHeaderCell";

[self.collectionView registerNib:[UINib nibWithNibName:@"HomeHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseIdentifierHeader];

3、实现Header

  • 实现CollectionView的viewForSupplementaryElementOfKind:代理方法,并设置Header的属性,如下:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
 
 UICollectionReusableView *headerView;
 if ([kind isEqualToString:UICollectionElementKindSectionHeader]){
       MGHeaderView *view = (MGHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:reuseIdentifierHeader forIndexPath:indexPath];
       view.headerLabel.text = [NSString stringWithFormat:@"MG这是header:%d",indexPath.section];
       headerView = view;
  }
 return headerView;
}

// 设置Header的尺寸
(CGSize)collectionView:(UICollectionView )collectionView layout:(UICollectionViewLayout)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
        CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
        return CGSizeMake(screenWidth, 280);
}

然后运行报错:
eason: '[<NSObject 0x7fc730d34a10> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the cycleScrollView.'
网上找了一通,但是也没能找到问题的解决方法,所以自己一步一步排查,总算发现问题所在,原因就是新建自定义headerView的时候,勾选了XIB file,然后在xib中的View父类默认UICollectionReusableView


image.png image.png

注意下这里的Class,必须要改为你对应的.h和.m文件的类名,因为创建的时候默认是UICollectionReusableView的,如果不改,然后xib中关联控件后运行就会出现上面那个setValue:forUndefinedKey的问题

相关文章

网友评论

    本文标题:iOS中UICollectionView 使用xib自定义头部遇

    本文链接:https://www.haomeiwen.com/subject/zfgfhqtx.html