UICollectionView的使用

来源:互联网 发布:mac口红flamingo 编辑:程序博客网 时间:2024/06/17 01:13

第一部分,三个协议方法,先介绍两个


前两个的用法和tableView的很像,第三个是头视图尾视图的协议。 (头视图尾视图,一样要写代理,写注册,缺少了就不行。) 注册以后,就不需要再去管理复用的问题了。这点就很简单。这个如果用好的话,会非常的简单。很多事情迎刃而解,否则使用tableView的话,需要三个tableView一起滑动,彼此之间需要观察,一旦变化随之变化,用scroller 的ContentOffset 来控制滑动,非常不科学,用这个的话三个就一起滑动了。

第二部分,构建

先得创建一个layout,UICollectionViewFlowLayout 这个类型的


//创建布局对象UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];//设置单元格的尺寸flowLayout.itemSize = CGSizeMake(80, 80);//设置头视图高度flowLayout.headerReferenceSize = CGSizeMake(0, 30);//flowlaout的属性,横向滑动flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//接下来就在创建collectionView的时候初始化,就很方便了(能直接带上layout)_myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, 320, 280) collectionViewLayout:flowLayout];_myCollectionView.tag = 200;_myCollectionView.backgroundColor = [UIColor greenColor]; _myCollectionView.delegate = self;_myCollectionView.dataSource = self;//添加到主页面上去 [self.view addSubview:_myCollectionView];//collectionCell的注册[_myCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"myheheIdentifier"];//collection头视图的注册   奇葩的地方来了,头视图也得注册[_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"Identifierhead”];#pragma mark -UICollectionViewDataSource//指定组的个数 ,一个大组!!不是一排,是N多排组成的一个大组(与下面区分)- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{    return 2;}//指定单元格的个数 ,这个是一个组里面有多少单元格,e.g : 一个单元格就是一张图片- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{    return 10;}//构建单元格- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{    if (collectionView.tag == 200) {        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myheheIdentifier" forIndexPath:indexPath];        cell.backgroundColor = [UIColor purpleColor];        return cell;    }}//组的头视图创建- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"Identifierhead" forIndexPath:indexPath];    headView.backgroundColor = [UIColor blueColor];    return headView;}//通过协议方法设置单元格尺寸- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{    CGFloat rd = arc4random()%90;    return CGSizeMake(90, rd);}


0 0
原创粉丝点击