//集合视图
//创建全局静态重用标识符
static NSString * collectionID = @"id";
@interface ViewController ()
//代理
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//特点一:创建CollectionView之前,先要创建CollectionView中的布局
UICollectionViewFlowLayout * layOut = [[UICollectionViewFlowLayout alloc]init];
//指定每个方格的尺寸
layOut.itemSize = CGSizeMake(310, 150);
//指定每个方格的边距 上、左、下、右
layOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//横向item最小间距
layOut.minimumInteritemSpacing = 0;
//设置纵向item最小间距
layOut.minimumLineSpacing = 10;
//更改CollectionView的滚动方向
// layOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//如果collectionView需要头尾视图则必须在layOut中指定头尾视图对应的尺寸
layOut.headerReferenceSize = CGSizeMake(320, 100);
UICollectionView * myCollectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layOut];
//特点四:在使用CollectionView的时候,切记将CollectionView的背景颜色清空
myCollectionView.backgroundColor = [UIColor clearColor];
//在创建collectionView的时候,同时就要指定当前CollectionView中要使用的cell
[myCollectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:collectionID];
//特点五:CollectionView的头尾视图
[myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
myCollectionView.delegate = self;
myCollectionView.dataSource = self;
[self.view addSubview:myCollectionView];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 24;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//特点二:重用
CustomCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionID forIndexPath:indexPath];
// cell.backgroundColor = [UIColor redColor];
//特点三:collectionView的cell只有contentView
for (UIView * v in [cell.contentView subviews]) {
[v removeFromSuperview];
}
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 100, 30)];
label.text = @"Cell";
[cell.contentView addSubview:label];
return cell;
}
//负责添加collectionView的头尾视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView * RView = nil;
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//头视图
RView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];
view.backgroundColor = [UIColor greenColor];
[RView addSubview:view];
}else{
}
return RView;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%ld",indexPath.item);
}