ios开发中,collectionView是必不可少的一个控件。在你没用到的时候他很陌生,用了之后会发觉,她就是tableView扩展出来的。不多说了,首先,先建立一个collectionViewCell 如图:
然后在.m控制器中添加collectionView
// 第一步: 遵守协议
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong) UICollectionView *collectionView;
@end
static NSString *CellIdentifier = @"Cell - Identifier";
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self initCollectionView];
}
- (void)initCollectionView
{
// 第二步 初始化一个布局类 (可以再这个类中设置cell的大小,边距)
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
// 保证每行只显示3个cell 每个cell间隔 10距离
CGFloat width = (self.view.frame.size.width - 20) / 3;
layout.itemSize = CGSizeMake(width, 200);
layout.minimumLineSpacing = 10; // 上下间隔 10
// 第三步 实例化 collection
self.collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.collectionView];
// 注册cell
[self.collectionView registerNib:[UINib nibWithNibName:@"CustomeCell" bundle:nil] forCellWithReuseIdentifier:CellIdentifier];
}
//返回组数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//返回row数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 30;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CustomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
CGFloat red = (arc4random_uniform(255) + 1) / 255.0;
CGFloat green = (arc4random_uniform(155) + 1) / 255.0;
CGFloat blue = (arc4random_uniform(200) + 1 )/ 255.0;
// 随机颜色
UIColor *randomColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
cell.imageView.backgroundColor = randomColor;
return cell;
}
// cell的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"当前点击了%ld + 1 个cell",indexPath.row);
}
看看效果 ,如图:
在这里只是简单的介绍控件,详细可以看苹果开发者文档中,collectionView的API.