iOSUICollectionView使用

   //创建一个layout布局类(也可以自定义,下篇中会有

    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];

    //设置布局方向为垂直流布局

    layout.scrollDirection = UICollectionViewScrollDirectionVertical;

   //设置布局方向为垂直流布局

    layout.scrollDirection =UICollectionViewScrollDirectionHorizontal;

    //设置每个item的大小为100*100

    layout.itemSize = CGSizeMake(100, 100);

    //设置行间距

     layout.minimumLineSpacing;

     //设置列间距

    layout.minimumInteritemSpacing;(根据父控件的宽来设置,需要计算)

    //创建collectionView 通过一个布局策略layout来创建

    UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];

    //代理设置

    collect.delegate=self;

    collect.dataSource=self;

 

    //注册item类型 这里使用系统的类型

    [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];

     [self.view addSubview:collect];

小结下:

-- sizeForItemAtIndexPath方法是设置cell的宽高,

-- insetForSectionAtIndex方法是设置一个section在CollectionView中的内边距;

-- minimumInteritemSpacingForSectionAtIndex方法是设置cell之间的最小边距(我下面会详细讲解这个方法);

-- minimumLineSpacingForSectionAtIndex方法是设置每行之间的距离;

注:必须实现的两个方法

 //返回每个分区的item个数

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{    

 return 10;

}

//返回每个item

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];  

    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];   

    return cell;

}

// 两个cell之间的最小间距,是由API自动计算的,只有当间距小于该值时,cell会进行换行(列间距)

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section

{

    return 15;

}

// 两行之间的最小间距(行间距)

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

{

    return 30;

}

// 该方法是设置一个section的上左下右边距(返回的间距是整体collectionView距离父控件之间的间距)

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    // 注意,这里默认会在top有+64的边距,因为状态栏+导航栏是64.

    // 因为我们常常把[[UIScreen mainScreen] bounds]作为CollectionView的区域,所以苹果API就默认给了+64的EdgeInsets,这里其实是一个坑,一定要注意。

    // 这里我暂时不用这个边距,所以top减去64

    // 所以这是就要考虑你是把Collection从屏幕左上角(0,0)开始放还是(0,64)开始放。

    return UIEdgeInsetsMake(10 10, 10, 10);

}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    return CGSizeMake(90, 90);

}

原文地址:https://www.cnblogs.com/hongyan1314/p/5795344.html