首先要遵循三个协议
// 必须遵守的三个协议
@interface CollectionViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
-
- (void)viewDidLoad {
[super viewDidLoad];
UICollectionViewFlowLayout *FlowLayout = [[UICollectionViewFlowLayout alloc] init];
// 设置每一个 cell 的大小 就是宽和高
[FlowLayout setItemSize:CGSizeMake(100, 100)];
// UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) 其中top和bottom控制的是距离顶部和底部的高度,并不能控制各个cellectionCell之间的距离,left和right能够控制各个cellectionCell之间的距离
FlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);// 设置每一个 cell 之间的边界
// 创建
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:FlowLayout];
collectionView.backgroundColor = [UIColor redColor];
//设置代理
collectionView.delegate = self;
collectionView.dataSource = self;
// 注册头部
// 注册 cell 否则无法显示
[ collectionView registerClass:[TestCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
[self.view addSubview:collectionView];
}
#pragma mark -- UICollectionViewCellde de 代理方法
// 控制有几个分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 3;
}
// 每个分区显示的 cell 的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 10;
}
// 返回 cell 的方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *idnetifier = @"collectionViewCell";
TestCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:idnetifier forIndexPath:indexPath];
return cell;
}
#pragma marl - UICollectionViewCell的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"点击的是第%ld个分区,的第%ld 行", (long)indexPath.section,(long)indexPath.row);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
第二部
创建 cell 继承自 UIcollectionViewCell
#import "TestCollectionViewCell.h"
@implementation TestCollectionViewCell
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.pictureImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 80, 80)];
self.pictureImage.image = [UIImage imageNamed:@"1.jpg"];
[self.contentView addSubview:self.pictureImage];
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 80, 30)];
self.titleLabel.text = @"标题";
[self.contentView addSubview:self.titleLabel];
}
return self;
}