使用collectionView的方法:
代码如下:
主要的是这三步:
1、创建layout
2、根据layout创建collectionView
3、设置代理
// 1、创建layout
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.minimumLineSpacing = 100; // 行距
layout.minimumInteritemSpacing = 10; // 列距
layout.itemSize=CGSizeMake((ScreeFrame.size.width - 40) / 3, (ScreeFrame.size.height - 80) / 4);
layout.sectionInset = UIEdgeInsetsMake(10, 10, 20, 10);
// 2、根据layout创建collectionView
self.collectionView_Subject = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 10, ScreeFrame.size.width, ScreeFrame.size.height - 64) collectionViewLayout:layout];
// 3、注册item 和 header Footer (根据用户需求)
[self.collectionView_Subject registerNib:[UINib nibWithNibName:@"SubjectCollectionViewCell" bundle:nil]forCellWithReuseIdentifier:@"SubjectId"];
[self.collectionView_Subject registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header_id"];
[self.collectionView_Subject registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer_id"];
// 4、设置代理
self.collectionView_Subject.delegate = self;
self.collectionView_Subject.dataSource = self;
self.collectionView_Subject.backgroundColor = [UIColor whiteColor];
[self addSubview:self.collectionView_Subject];
集合视图的代理就和tableView类似了:设置sections、rows、cell、以及头/尾视图。
1> 设置item大小:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
2> 设置头视图和尾视图
/**
* 根据样式判断是头还是尾
* UICollectionElementKindSectionFooter
* UICollectionElementKindSectionHeader
*/
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
// 头视图大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
return CGSizeMake(ScreeFrame.size.width, ScreeFrame.size.height / 12);
}
// 尾视图大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
return CGSizeMake(ScreeFrame.size.width, 10);
}