天天看點

iOS 單元格CollectionView簡介

前兩個的用法和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);

}