UICollectionView 和 UICollectionViewController 類是iOS6 新引進的API,用於展現集合視圖,佈局更加靈活,可實現多列布局,用法相似於UITableView 和 UITableViewController 類。佈局
使用UICollectionView 必須實現UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout這三個協議。spa
下面先給出經常使用到的一些方法。(只給出經常使用的,其餘的能夠查看相關API) orm
#pragma mark -- UICollectionViewDataSource it
//定義展現的UICollectionViewCell的個數 io
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section queue
{ 方法
return 30; layout
} 協議
//定義展現的Section的個數 margin
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//每一個UICollectionView展現的內容
-(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
//定義每一個UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(96, 100);
}
//定義每一個UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(5, 5, 5, 5);
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被選中時調用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
}
//返回這個UICollectionView是否能夠被選擇
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}