最近使用了下UICollectionView 我一直都是纯代码 网上纯代码创建UIcollectionView的好少 额不说废话了 直接贴代码
//这个是创建约束的 包括设置行间距 单元格间距等
UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayoutalloc] init];
//这个是设置单元格大小的
flowLayout.itemSize=CGSizeMake(145,220);
//设置单元格间距
flowLayout.minimumInteritemSpacing=10;
//设置行间距
flowLayout.minimumLineSpacing=10;
//设置headerView的
[flowLayout setHeaderReferenceSize:CGSizeMake(DEF_SCREEN_WIDTH,35)];
//设置拖动方向的
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
//创建UIcollectionView
self.collectionView=[[UICollectionViewalloc]initWithFrame:CGRectMake(10, 74,DEF_SCREEN_WIDTH-20,DEF_SCREEN_HEIGHT-74-49)collectionViewLayout:flowLayout];
//注册cell 的 不写会崩……
[self.collectionViewregisterClass:[LayerCollectionCellclass] forCellWithReuseIdentifier:@"cell"];
//注册 header 不需要header 可以不写
[self.collectionViewregisterClass:[CollectionHeaderViewclass] forSupplementaryViewOfKind:@"UICollectionElementKindSectionHeader"withReuseIdentifier:@"headerView"];
self.collectionView.delegate=self;
self.collectionView.bounces=NO;
self.collectionView.backgroundColor=[UIColorclearColor];
self.collectionView.dataSource=self;
[self.viewaddSubview:self.collectionView];
//返回每个section 的cell 数量
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 30;
}
//返回section的数量
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//创建cell
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellName=@"cell";
LayerCollectionCell *cell=[collectionViewdequeueReusableCellWithReuseIdentifier:cellNameforIndexPath:indexPath];
if (cell== nil) {
cell=[[LayerCollectionCellalloc]initWithFrame:CGRectMake(0,0, 145, 220)];
}
cell.backgroundColor=[UIColorwhiteColor];
[cellinitView];
cell.image.image=[UIImageimageNamed:@"layerHead"];
// [email protected]""
return cell;
}
//选中cell执行的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"%@",indexPath);
}
//创建header 的这个 方法里也可以创建footer 要想创建header 必须新建一个类 继承自 UICollectionReusableView 下面的CollectionHeaderView 类就是继承自它 可以根据kind 设置是footer 还是header 加个判断就可以 我这里没有加需要的童鞋自己加上去吧
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionReusableView *reusableView=nil;
CollectionHeaderView *view=[collectionViewdequeueReusableSupplementaryViewOfKind:@"UICollectionElementKindSectionHeader"withReuseIdentifier:@"headerView"forIndexPath:indexPath];
reusableView=view;
return reusableView;
}
//加一个返回不同header 高度的方法
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
if (section == 0) {
return CGSizeMake(DEF_SCREEN_WIDTH, 105);
}else{
return CGSizeMake(DEF_SCREEN_WIDTH, 35);
}
}