UICollectionView

基本使用

  • 注意点:
    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
    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;
  • 将UICollectionView添加到控制器
[self.view addSubview:collectionView];
  • 设置数据源
collectionView.dataSource = self;
  • 注册cell
 [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;
}

布局(针对流水对象)

  • 流水布局:调整cell尺寸
//创建布局
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
flow.itemSize = CGSizeMake(160, 160);
  • 设置最小行间距
    flow.minimumLineSpacing = 0;
  • 设置最小的item间距
 flow.minimumInteritemSpacing = 0;
  • 设置滚动方向(水平)
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
  • 设置内间距,让第一张和最后一张图片每次在colectionView的中间
    CGFloat margin = (self.view.bounds.size.width - 160) * 0.5;
    flow.sectionInset = UIEdgeInsetsMake(0, margin, 0, margin);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iOS开发疯狂者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值