iOS开发之UICollectionView

   UICollectionView类是iOS6 新引进的API,用于展示集合视图,布局更加灵活,可实现多列布局,用法类似于UITableView 类。

   下面我介绍下UICollectionView它的使用:

   说明:

   1.我已定义的一个属性@property (nonatomic, strong) UICollectionView *collectionView;

   2.UICollectionView的cell我自定义了一个CollectionCell.h继承UICollectionViewCell

一、实现UICollectionViewDataSource,UICollectionViewDelegate协议

二、创建UICollectionView

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(_collectionCellW, _collectionCellH); // item尺寸
    flowLayout.sectionInset = UIEdgeInsetsMake(0, _horizontalFloat, _verticalFloat, _horizontalFloat); // item间距
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(marginX, marginY, collectionViewW, collectionViewH)         collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor clearColor]; // UICollectionView背景颜色

    _collectionView.allowsSelection = NO;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    // 注册cell(这个必须要写)
    [_collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];

三、实现方法

#pragma mark - collectionView代理

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.models.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    int row = (int)indexPath.row;
    static NSString *ident = @"cell";
    CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ident forIndexPath:indexPath];
    [cell sizeToFit];
    
    Bank *bank = self.models[row];
    cell.bank = bank;
    
    return cell;
}


//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}

总结:按照以上步骤就大功告成了。其实UICollectionView和UITableView很像的。初接触它时会感觉它太麻烦很多用法搞不懂,其实你多用几次就会发现它很方便简单的,想想UITableView你运用了多少次。一句话给大家“编程需要练习和思考”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值