基本使用
- 注意点:
1.UICollectionView必须要有布局参数
2.如果要使用UICollectionViewCell,必须要通过注册
3.cell必须要自定义,系统cell没有任何子控件
我们创建一个photoCell类来管理我们的cell(带有xib)
一个ID的全局变量,用来注册cell
static NSString * const ID = @"cell";
在ViewController.m中实现(遵守数据源协议)(后续可以抽取方法)
//流水布局:调整cell尺寸
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flow];
collectionView.center = self.view.center;
collectionView.backgroundColor = [UIColor brownColor];
collectionView.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 200);
//取消滚动条
collectionView.showsHorizontalScrollIndicator = NO;
[self.view addSubview:collectionView];
collectionView.dataSource = self;
[collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([photoCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
实现数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//我们外界需要给photoCell的Xib设置image属性,所以我们就在photoCell类中创建一个image属性(缺什么补什么)
photoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
cell.image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld", indexPath.row + 1]];
return cell;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
}
在photoCell.h中实现
@property(nonatomic,strong) UIImage *image;
在photoCell.m中实现
//创建一个类扩展,因为我们需要将Xib里面的image控件设置一个属性,之后给他赋值,我们连线,为photoView
@interface photoCell()
@property (strong, nonatomic) IBOutlet UIImageView *photoView;
@end
//给我们之前设置的image属性赋值,利用set方法,之后将图片加载到Xib的image控件
- (void)setImage:(UIImage *)image{
_image = image;
self.photoView.image = image;
}
布局(针对流水对象)
//创建布局
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
flow.itemSize = CGSizeMake(160, 160);
flow.minimumLineSpacing = 0;
flow.minimumInteritemSpacing = 0;
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
- 设置内间距,让第一张和最后一张图片每次在colectionView的中间
CGFloat margin = (self.view.bounds.size.width - 160) * 0.5;
flow.sectionInset = UIEdgeInsetsMake(0, margin, 0, margin);