IOS-UICollectionView的基本使用以及添加headerView

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-23 06:34   98   0

UICollectionView 说白了就是照片墙

在展示类的App中也很常见,比如:瀑布流。

下面说一下如何简单的使用 和如何添加headerView 让他也拥有类似于tableview的headerView的效果

UIKIT_EXTERN NSString *const UICollectionElementKindSectionHeader; //定义好Identifier

static NSString *const HeaderIdentifier = @"HeaderIdentifier";



UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; //此处自动布局,我没有写任何东西 布局样式都在cell中

_collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-70) collectionViewLayout:layout];


self.collectionView.dataSource = self;

self.collectionView.delegate = self;

self.collectionView.showsVerticalScrollIndicator = NO;

//此处需要注册才可以使用

[self.collectionView registerClass:[DiaperColectionCell class] forCellWithReuseIdentifier:BrankViewCellIdentifier];

[self.collectionView registerClass:[MYBrandHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HeaderIdentifier];

[self.view addSubview:self.collectionView];


下面执行代理方法 跟tableview 一样的

#pragma mark -

#pragma mark collectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

//section数量

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

//数据数量

}

//设置元素大小

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

return (返回一个Item的 宽高)

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

//此处就是自定义好的cell

}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

//UICollectionView被选中时调用的方法

}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

{

MYBrandHeaderView *headReusableView;

//此处是headerView

if (kind == UICollectionElementKindSectionHeader) {

headReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:HeaderIdentifier forIndexPath:indexPath];

headReusableView.frame = CGRectZero;

headReusableView.delegate = self;

headReusableView.modeNumber = 1;

[((MYBrandHeaderView *)headReusableView) setData:self.headerDict];

}

return headReusableView;

}


//执行的 headerView 代理 返回 headerView 的高度

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section

{

CGFloat height = [self.topView getHeight];

return CGSizeMake(320, height);

}



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP