[iOS开发]UICollectionView瀑布流的学习

39 篇文章 0 订阅

写在前面

我们很多都会使用 UITableView ,UICollectionView 瀑布流也是与其十分相似的一个十分强大的控件。
好处有很多:

  1. 支持水平和垂直两种方向的布局
  2. 通过layout配置方式进行布局
  3. 类似于TableView中的cell特性外,CollectionView中的Item大小和位置可以自由定义
  4. 通过layout布局回调的代理方法,可以动态的定制每个item的大小和collection的大体布局属性
  5. 更加强大的一点是可以完全自定义一套layout布局方案,可以实现意想不到的效果

使用

上代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置item的行间距和列间距
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 5;
    // 设置item的大小
    CGFloat itemW = (selfWidth - 25) / 4 ;
//    layout.itemSize = CGSizeMake(itemW, itemW);
    // 设置每个分区的 上左下右 的内边距
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    // 设置区头和区尾的大小
    layout.headerReferenceSize = CGSizeMake(selfWidth, 65);
    layout.footerReferenceSize = CGSizeMake(selfWidth, 65);
    // 设置分区的头视图和尾视图 是否始终固定在屏幕上边和下边
//    layout.sectionHeadersPinToVisibleBounds = YES;
//    layout.sectionFootersPinToVisibleBounds = YES;
    // 设置滚动条方向
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    
    _myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, selfWidth, selfHeight - 200)collectionViewLayout:layout];
    [self.view addSubview:_myCollectionView];
    //使用前先注册
    [_myCollectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"myFirstCellId"];
    [_myCollectionView registerClass:[MyCollectionReusableHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myFirstHeader"];
    [_myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myFirstFooter"];
    //设置代理
    _myCollectionView.delegate = self;
    _myCollectionView.dataSource = self;
    
    _myCollectionView.allowsSelection = YES;
}

#pragma mark - collectionview 数据源方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;   //返回section数
}

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

    return 12;  //每个section的Item数
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MyCollectionViewCell *cell = [_myCollectionView dequeueReusableCellWithReuseIdentifier:@"myFirstCellId" forIndexPath:indexPath];
    // 外界在此给Item添加模型数据
    
    return cell;
}
//根据indexpath设置每个item大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    CGFloat itemW = (selfWidth - 25) / 4 ;
    if ((indexPath.row - 1) % 3 == 0) {
        return CGSizeMake(itemW * 2 + 5, itemW);
    } else {
        return CGSizeMake(itemW, itemW);
    }
}

#pragma mark - 头部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"myFirstHeader" forIndexPath:indexPath];
        // ID必须与注册ID一样
        return headView;
    } else {
        UICollectionReusableView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"myFirstFooter" forIndexPath:indexPath];
        // ID必须与注册ID一样
        footView.backgroundColor = [UIColor grayColor];
        return footView;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(selfWidth, 65);
//    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    
    return CGSizeMake(selfWidth, 65);
//    return CGSizeZero;
}

#pragma mark - 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSLog(@"%@", indexPath);
}

效果:
在这里插入图片描述
此外,它的layout布局也可以自定义,实现一些有趣的功能:
调用顺序是:

  1. 使用"prepareLayout"方法去执行一些CollectionView所需要的布局信息的预先计算操作。
  2. 使用"collectionViewContentSize"方法去返回根据你最初计算的整个内容区域的总体大小。
  3. 使用"layoutAttributesForElementsInRect:"方法来返回指定区域的单元格与视图属性。
    下面给出一个样例:
#pragma mark - 下面的是自定义的layout
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    MyLayout * layout = [[MyLayout alloc]init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.itemCount = 100;
    layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    layout.heightArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 100; ++i) {
        [layout.heightArray addObject:[NSNumber numberWithFloat:arc4random() % 150 + 40]];
    }
     UICollectionView * collect  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 100, selfWidth, selfHeight - 200) collectionViewLayout:layout];
    collect.delegate = self;
    collect.dataSource = self;
    
    [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
  
    [self.view addSubview:collect];
    
    
}
 
 
 
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 100;
}
-(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;
}
@implementation MyLayout {
    //这个数组就是我们自定义的布局配置数组
    NSMutableArray * _attributeAttay;
}
//数组的相关设置在这个方法中
//布局前的准备会调用这个方法
- (void)prepareLayout {
    if (!_count) {
        _count = [NSNumber numberWithInt:0];
    }
    _attributeAttay = [[NSMutableArray alloc] init];
    [super prepareLayout];
    //演示方便 我们设置为静态的2列
    //计算每一个item的宽度
    float WIDTH = ([UIScreen mainScreen].bounds.size.width - self.sectionInset.left - self.sectionInset.right - self.minimumInteritemSpacing) / 2;
    //定义数组保存每一列的高度
    //这个数组的主要作用是保存每一列的总高度,这样在布局时,我们可以始终将下一个Item放在最短的列下面
    CGFloat colHight[2] = {self.sectionInset.top, self.sectionInset.bottom};
    //itemCount是外界传进来的item的个数 遍历来设置每一个item的布局
    for (int i = 0; i < _itemCount; i++) {
        //设置每个item的位置等相关属性
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        //创建一个布局属性类,通过indexPath来创建
        UICollectionViewLayoutAttributes *attris = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        //随机一个高度 在40——190之间
        CGFloat height = 0;
        if (_heightArray.count > _count.intValue) {
            NSNumber *num = _heightArray[_count.intValue];
            _count = [NSNumber numberWithInt:_count.intValue + 1];
            height = num.floatValue;
        }
        
        //哪一列高度小 则放到那一列下面
        //标记最短的列
        int width = 0;
        if (colHight[0] < colHight[1]) {
            //将新的item高度加入到短的一列
            colHight[0] = colHight[0] + height + self.minimumLineSpacing;
            width = 0;
        } else {
            colHight[1] = colHight[1] + height + self.minimumLineSpacing;
            width = 1;
        }
        //设置item的位置
        attris.frame = CGRectMake(self.sectionInset.left + (self.minimumInteritemSpacing + WIDTH) * width, colHight[width] - height - self.minimumLineSpacing, WIDTH, height);
        [_attributeAttay addObject:attris];
    }
    //设置itemSize来确保滑动范围的正确 这里是通过将所有的item高度平均化,计算出来的(以最高的列位标准)
    if (colHight[0] > colHight[1]) {
        self.itemSize = CGSizeMake(WIDTH, (colHight[0] - self.sectionInset.top) * 2/ _itemCount - self.minimumLineSpacing);
    } else {
        self.itemSize = CGSizeMake(WIDTH, (colHight[1] - self.sectionInset.top) * 2/ _itemCount - self.minimumLineSpacing);
    }
}
//这个方法中返回我们的布局数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return _attributeAttay;
}

实现效果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值