56.UICollectionView的基本使用

- (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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值