UICollectionViewController在使用之前必须要做的两件事:
一. 为UICollectionViewController指定布局方式
二. 为UICollectionViewController注册单元格
流式布局小例子:
#import "SZMProductCollectionViewController.h"#import "SZMProductModel.h"#import "SZMProductCell.h"@interface SZMProductCollectionViewController ()@property (nonatomic,strong)NSArray *products;@end@implementation SZMProductCollectionViewControllerstatic NSString * const reuseIdentifier = @"Cell";- (NSArray *)products{ if (!_products) { //加载数据 //获取json文件路径 NSString *path = [[NSBundle mainBundle]pathForResource:@"more_project.json" ofType:nil]; //把json文件加载到一个NSData对象中 NSData *jsonData = [NSData dataWithContentsOfFile:path]; //把NSData转换为一个字典数组 NSArray *arrayDicts = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil]; //把字典数组转换为一个模型数组 NSMutableArray *modelArray = [NSMutableArray array]; for (NSDictionary *dict in arrayDicts) { SZMProductModel *modle = [SZMProductModel productWithDict:dict]; [modelArray addObject:modle]; } _products = modelArray; } return _products;}- (instancetype)init{ //创建一个流式布局对象 UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init]; //设置每个cell的大小 layout.itemSize = CGSizeMake(80, 80); //设置每个cell间的最小水平间距 layout.minimumInteritemSpacing = 0; //设置每个cell间的行间距 layout.minimumLineSpacing = 5; //设置每一组距离四周的内边距 layout.sectionInset = UIEdgeInsetsMake(5, 0, 0, 0); //返回 return [super initWithCollectionViewLayout:layout]; }- (void)viewDidLoad { [super viewDidLoad]; //注册类:注册单元格:告诉系统(UICollectionView),当缓存池中没有现成的cell对象以后,要创建哪个类的对象作为cell来使用 //[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifier]; //注册xib UINib *nib = [UINib nibWithNibName:@"SZMProductCell" bundle:nil]; [self.collectionView registerNib:nib forCellWithReuseIdentifier:reuseIdentifier]; [self.collectionView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg"]]]; }- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{ SZMProductModel *model = self.products[indexPath.row]; NSLog(@"%@",model.title);}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}#pragma mark//返回多少组- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1;}//每组返回多少格子- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.products.count;}//每个格子返回什么内容- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { //1.获取数据 SZMProductModel *model = self.products[indexPath.row]; //2.创建cell SZMProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath]; //3.为cell设置数据 cell.product = model; return cell;}@end