美文网首页糖糖的iOS专题UICollectionView程序员
创建一个UICollectionView /头视图

创建一个UICollectionView /头视图

作者: 我的梦想之路 | 来源:发表于2016-06-02 17:01 被阅读286次
创建一个UICollectionView 的方式:
//声明布局方式

UICollectionViewFlowLayout*layout=[[UICollectionViewFlowLayoutalloc]init];

//设置对齐方式

[layoutsetScrollDirection:UICollectionViewScrollDirectionVertical];

//设置cell间距

layout.minimumInteritemSpacing=2;

//设置cell行距

layout.minimumLineSpacing=2;

//设置头视图的大小

//layout.headerReferenceSize=CGSizeMake(320.0, 150.0);

_collec=[[UICollectionViewalloc]initWithFrame:CGRectMake(0.0,214.0,W,H)collectionViewLayout:layout];

_collec.delegate=self;

_collec.dataSource=self;

_collec.backgroundColor=[UIColorwhiteColor];

_collec.tag=100;

[self.viewaddSubview:_collec];

//注册表格单元格

[_collecregisterNib:[UINibnibWithNibName:@"ZuoPinCell"bundle:nil]forCellWithReuseIdentifier:@"zuopinCell"];

//注册collection头视图

[_collecregisterClass:[UICollectionReusableViewclass]forSupplementaryViewOfKind:UICollectionElementKindSectionHeaderwithReuseIdentifier:@"header"];

实现头视图协议方式:


//实现头视图

//提供头视图的大小

- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

returnCGSizeMake(320.0,50.0);

}

//获取头视图的方法

- (UICollectionReusableView*)collectionView:(UICollectionView*)collectionView viewForSupplementaryElementOfKind:(NSString*)kind atIndexPath:(NSIndexPath*)indexPath{

//创建UICollectionReusableView视图

UICollectionReusableView*header;

if([kindisEqualToString:UICollectionElementKindSectionHeader]) {

header=[collectionViewdequeueReusableSupplementaryViewOfKind:kindwithReuseIdentifier:@"header"forIndexPath:indexPath];

//添加头视图内容

[selfaddBtn];

//头视图添加view

[headeraddSubview:_btn];

}

returnheader;

}

//collection头视图

- (void)addBtn{

UIButton*btn=[UIButtonbuttonWithType:UIButtonTypeCustom];

btn.frame=CGRectMake(0.0,0,320.0,50.0);

[btnsetTitle:@"上传+作品"forState:UIControlStateNormal];

btn.backgroundColor=[UIColorbrownColor];

[btnaddTarget:selfaction:@selector(handleWorkUp)forControlEvents:UIControlEventTouchUpInside];

[self.viewaddSubview:btn];

_btn=btn;

}
UICollectionView的头视图步骤:

1.创建一个继承UICollectionReusableView的子类

2.实现UICollectionViewDelegateFlowLayout协议

3.注册头视图

4.实现协议方法

5.如果需要想要大小的单元格:实现

//设置单元格大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

return CGSizeMake(100.0,100.0);

}

相关文章

网友评论

    本文标题:创建一个UICollectionView /头视图

    本文链接:https://www.haomeiwen.com/subject/gvjkdttx.html