本章通過(guò)先總體介紹UICollectionView及其常用方法眼俊,再結(jié)合一個(gè)實(shí)例意狠,了解如何使用UICollectionView。
UICollectionView 和 UICollectionViewController 類是iOS6 新引進(jìn)的API疮胖,用于展示集合視圖环戈,布局更加靈活,可實(shí)現(xiàn)多列布局澎灸,用法類似于UITableView 和 UITableViewController 類院塞。
使用UICollectionView 必須實(shí)現(xiàn)UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout這三個(gè)協(xié)議。
下面先給出常用到的一些方法性昭。(只給出常用的拦止,其他的可以查看相關(guān)API)
#pragma mark -- UICollectionViewDataSource
//定義展示的UICollectionViewCell的個(gè)數(shù)
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 30;
}
//定義展示的Section的個(gè)數(shù)
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//每個(gè)UICollectionView展示的內(nèi)容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = @"GradientCell";
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];
return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//定義每個(gè)UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(96, 100);
}
//定義每個(gè)UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(5, 5, 5, 5);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被選中時(shí)調(diào)用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
}
//返回這個(gè)UICollectionView是否可以被選擇 ?
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}