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你运用了多少次。一句话给大家“编程需要练习和思考”。