ViewController.m
#import "ViewController.h"
#define HCWidth self.view.frame.size.width
#define HCHeigh self.view.frame.size.height
//4.遵守协议
@interface ViewController ()<UICollectionViewDelegate , UICollectionViewDataSource>{
NSArray *arrimG;
}
@end
static NSString *reuseCell = @"123";
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建流水布局
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//格子的大小
layout.itemSize = CGSizeMake(80, 100);
//行间距
layout.minimumLineSpacing = 15;
//列间距
layout.minimumInteritemSpacing = 15;
//分区间距
layout.sectionInset = UIEdgeInsetsMake(15, 30, 30, 15);
//
//网格视图 (表格 -> 需要注册,需要创建布局)
//1.frame
UICollectionView *clV = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
//2.数据源和代理
clV.delegate = self;
clV.dataSource = self;
//3.添加到主视图
[self.view addSubview:clV];
//注册网格cell
[clV registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseCell];
//给数组赋值
arrimG = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
//设置视图的背景颜色
clV.backgroundColor = [UIColor whiteColor];
}
//分区个数 (几组)
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 2;
}
//每个分区有几个item (小格子的个数)
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
if (section == 0) {
return 7;
}else{
return 3;
}
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//创建重用标识符
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseCell forIndexPath:indexPath];
//设置格子的背景颜色
cell.backgroundColor = [UIColor redColor];
//初始化图片框
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
//添加图片
imgV.image = [UIImage imageNamed:arrimG[indexPath.row]];
//添加到网格里面
[cell addSubview:imgV];
//设置文字
UILabel *lb1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 80, 80, 20)];
//设置文字
lb1.text = arrimG[indexPath.row];
//文字居中
lb1.textAlignment = NSTextAlignmentCenter;
//添加到网格里面
[cell addSubview:lb1];
return cell;
}