- (id)init
{
//UICollectionViewLayout // 布局对象决定了将来CollectionView上每一个Cell显示的方式
// 创建一个布局对象UICollectionViewFlowLayout是UICollectionViewLayout的子类
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
// 设置每一个cell的宽高 (cell在CollectionView中称之为item)
layout.itemSize = CGSizeMake(80, 80);
// 设置item行与行之间的间隙
layout.minimumLineSpacing = 10;
// 设置item列与列之间的间隙
layout.minimumInteritemSpacing = 0;
// 设置CollectionView距离上边和下边的距离
//layout.headerReferenceSize = CGSizeMake(0, 100);
//layout.footerReferenceSize = CGSizeMake(0, 200);
// 设置CollectionView内容部分距离控制器view上下左右的边距
// 上/左/下/右
layout.sectionInset = UIEdgeInsetsMake(layout.minimumLineSpacing, 0, 0, 0);
// 在初始化的时候传入自己创建的布局对象
if (self = [super initWithCollectionViewLayout:layout]) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"产品推荐";
// 告诉系统将来需要创建什么样的cell(在获取cell之前必须先注册一个cell到系统中)
//[self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:NJIdentifier];
//self.products;
// 如果item(cell) 是通过xib描述的, 就要先注册xib
UINib *nib = [UINib nibWithNibName:@"NJProductItem" bundle:nil];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:NJIdentifier];
// 设置控制器view的背景颜色
self.collectionView.backgroundColor = [UIColor whiteColor];
}
#pragma mark - 数据源方法
// 告诉系统一共有多少组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
// 告诉系统第section组有多少行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 10;
}
// 告诉系统indexPath的第Section组的item行显示什么内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// indexPath.section;// 第几组
// indexPath.item;// 第几个
// 1.从缓存池中获取cell
NJProductItem *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NJIdentifier forIndexPath:indexPath];
//如果从缓存池中取不到可用的cell,系统会根据注册的cell进行创建
// 2.设置数据
cell.product = self.products[indexPath.item];
// 3.返回cell
return cell;
}
#pragma mark- UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
// 1.获取点击的那一个item对应的模型
NJProduct *product = self.products[indexPath.item];
NSLog(@"%@", product.title);
}
56.UICollectionView的基本使用
最新推荐文章于 2021-11-03 21:46:18 发布