1.初始化一个collectionView
UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
layout.minimumInteritemSpacing = 5;
layout.minimumLineSpacing = 5;
//定义每个item的大小
layout.itemSize = CGSizeMake(120, 150);
_collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
_collectionView.backgroundColor = [UIColor whiteColor];
_collectionView.delegate = self;
_collectionView.dataSource = self;
//注册cell
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
[self.view addSubview:_collectionView];
2.实现代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return _dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
imageV.image = [UIImage imageNamed:_dataArray[indexPath.row]];
UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 21)];
label.text = [NSString stringWithFormat:@"第%ld张图", indexPath.row];
label.textAlignment = NSTextAlignmentCenter;
//一定要先移除之前的,不然会重叠
for (UIView * view in cell.contentView.subviews) {
[view removeFromSuperview];
}
[cell.contentView addSubview:imageV];
[cell.contentView addSubview:label];
return cell;
}