UICollectionView Section 纯代码代码控制 HeaderView和FooterVi

如果你在想HeaderView和FooterView怎么用代码控制显示,,说明你对Collectionview基本用法已经掌握(网上相关文章也很多),这里我就不在多介绍了。

UICollectionView显示Section好像不如UITableView那么容易,常用会有两种做法:

1.Xib或者Storyboard 在属性一栏中设置一下

如图所示,这里不多做介绍(网上有好多已经详细介绍–xib设置sectionview)。

2.代码设计Section的header和Footer

好多小伙伴都在找UICollectionView是否有这么个属性,比如上图说到Accessories什么的,其实不然。大家首先要搞明白意见事情,header和footer是追加视图,属于layout中的,所以要代码设置section要在UICollectionViewFlowLayout:

– (UICollectionViewFlowLayout *) flowLayout{UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];flowLayout.。。。。。。//各属性设置flowLayout.headerReferenceSize = CGSizeMake(300.0f, 50.0f); //设置head大小flowLayout.footerReferenceSize = CGSizeMake(300.0f, 50.0f);return flowLayout;} 如果你用的是Xib或者Storyboard,不想在上图属性设置,想用代码:- (void)viewDidLoad {[super viewDidLoad];//这个地方一定要写,不然会crash[_ui_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"GradientCell"];[_ui_collectionView registerClass:[RecipeCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];//代码控制header和footer的显示UICollectionViewFlowLayout *collectionViewLayout = (UICollectionViewFlowLayout *)_ui_collectionView.collectionViewLayout;collectionViewLayout.headerReferenceSize = CGSizeMake(375, 50);}

其中_ui_collectionView是:

@property (weak, nonatomic) IBOutlet UICollectionView *ui_collectionView;。

说明(这部分说明可以参见xib设置sectionview):

当然要让上述代码起作用还要注册UICollectionReusableView的派生类(上述代码中的RecipeCollectionReusableView),还要实现:

– (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{UICollectionReusableView *reusableview = nil;if (kind == UICollectionElementKindSectionHeader){RecipeCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];reusableview = headerView;}// if (kind == UICollectionElementKindSectionFooter)// {//RecipeCollectionReusableView *footerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"FooterView" forIndexPath:indexPath];////reusableview = footerview;// }reusableview.backgroundColor = [UIColor redColor];return reusableview;}希望对大家有帮助!

运行结果:

红色为header。

青春在我的心中是苦涩的又是甘甜的,是精致的又是粗糙的,

UICollectionView Section 纯代码代码控制 HeaderView和FooterVi

相关文章:

你感兴趣的文章:

标签云: