纵向横向瀑布流

本篇文章主要介绍瀑布流的实现原理,demo以原理为主,随便写了写,封装性不好,如果拿去直接用需要修改的地方是比较多的。所以此文章仅供学习,想直接用的小伙伴需要多费些功夫了。

话不多说,先看看效果图

瀑布流.gif

首先介绍一下用到的控件

这里我们用的是 UICollectionView 它的优点咱们不多说,最大的优点单元格可复用,当然你非要用 UIView 循环创建那我也没话说。
要用 UICollectionView 实现一个瀑布流,只用代理方法是不可能的,这里我们要用到 UICollectionView 的布局类 UICollectionViewFlowLayout
我们要去继承 UICollectionViewFlowLayout 自定义一个新的布局类,瀑布流的实现就是依靠我们自定义的布局类。

再来看看自定义布局类中用到的方法

//当collectionView的frame有新改变(发生移动)时调用,其若返回YES则重新布局
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}

/**
 *  准备好布局时调用
 *  布局准备方法 当collectionView的布局发生变化时 会被调用
 *  通常是做布局的准备工作 itemSize.....
 *  UICollectionView 的 contentSize 是根据 itemSize 动态计算出来的
调用顺序 ···· 1
 */
- (void)prepareLayout{ 
}

//返回collectionView视图中所有视图的属性(UICollectionViewLayoutAttributes)数组
调用顺序 ···· 3(每个应的item属性方法调用完后还会调用此方法)
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return nil;
}

//返回indexPath对应item的属性
调用顺序 ···· 4
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    return nil;
}

//设置collectionView的可显示范围
调用顺序 ···· 2
- (CGSize)collectionViewContentSize{
    return CGSizeMake(0, 0);
}

瀑布流的原理就是手动计算每个 item 的 frame 然后交给 collectionView 布局类的内容视图(包括头尾视图、每个单元格等)属性数组。

先看比较简单的,垂直瀑布流的实现步骤

1.复写 prepareLayout 方法,准备工作,此时的 collectionView 就像一个空的 scrollView 所有的 item 都需要我们自己手动的确定他的 frame 就像一个画板,我们需要把视图都画在这个画板上。
/**
 *  准备好布局时调用
 *  布局准备方法 当collectionView的布局发生变化时 会被调用
 *  通常是做布局的准备工作 itemSize.....
 *  UICollectionView 的 contentSize 是根据 itemSize 动态计算出来的
 */
- (void)prepareLayout{
    
    //item的最小间距
    CGFloat space = self.minimumInteritemSpacing;
    CGFloat contentSize = self.collectionView.bounds.size.width - self.sectionInset.left - self.sectionInset.right;
    //每个单元格的宽度
    CGFloat itemWidth = (contentSize - (space * (self.lineNum-1)))/self.lineNum;
    //根据宽度计算每个单元格的属性
    [self computeAttributesWithItemWidth:itemWidth];
}

计算每个单元格的 attributes 方法,我们保存每一列的总高度,在创建每个单元格的 attributes 时挑选最短的那一列,把当前单元格添加到这个最短列

- (void)computeAttributesWithItemWidth:(CGFloat)width{
    
    //存储每列个数和每列总高度的数组
    CGFloat columnHeight[self.lineNum];
    CGFloat columnNum[self.lineNum];
    //初始化数组
    for (int i = 0; i < self.lineNum; i ++) {
        columnNum[i] = 0;
        //sectionInset  UIEdgeInsets类型  边距
        columnHeight[i] = self.sectionInset.top;
    }
    
    //循环创建每个单元格的 attributes
    for (int i = 0; i < self.dataList.count; i ++) {
        int index = [self computerMinHeightWithArray:columnHeight];
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        //计算每个item的位置,大小
        CGFloat itemX = index * (width+self.minimumLineSpacing) + self.sectionInset.left;
        CGFloat itemY = columnHeight[index];
        CGFloat itemHeight = [self makeNum];
        
        attributes.frame = CGRectMake(itemX, itemY, width, itemHeight);
        
        [self.attributesArray addObject:attributes];
        
        columnHeight[index] += itemHeight+self.minimumInteritemSpacing;
        columnNum[index] ++;
    }
    
    //计算最高列
    int maxIndex = [self computerMaxHeightWithArray:columnHeight];
    _maxHeight = columnHeight[maxIndex];
    //计算 item 的大小平均值,这样可以大致确定 collectionView 的内容视图尺寸,但不是太准确
    CGFloat aveHeight = (columnHeight[maxIndex] - self.sectionInset.top - columnNum[maxIndex]*self.minimumLineSpacing)/columnNum[maxIndex];
    self.itemSize = CGSizeMake(width, aveHeight);
    
}
2.在 layoutAttributesForElementsInRect: 方法中 return 所有 item 的 attributes 数组
//返回collectionView视图中所有视图的属性(UICollectionViewLayoutAttributes)数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.attributesArray;
}
3.写完上一步,这个垂直瀑布流的布局类基本写完了,但是我们发现内容尺寸还是不太对,之前这个内容尺寸是布局类根据自身的属性 itemSize 来计算的,而 itemSize 取的是平均值,这样算出的内容尺寸会有些偏差,我们再重写一下 collectionViewContentSize 方法
//内容尺寸
//取最高列的高度作为内容尺寸的高度
- (CGSize)collectionViewContentSize{
    
    return CGSizeMake(self.collectionView.bounds.size.width, _maxHeight);
    
}

垂直的写完了,再来看看水平的是怎么实现的

1.同样的首先去复写 prepareLayout 方法,在此方法里面计算每个 item 的 attributes
- (void)prepareLayout{
    [self computeAttributes];
}
//计算每个单元格的属性
- (void)computeAttributes{
    
    //存贮每行个数
    NSMutableArray *lineNum = [[NSMutableArray alloc] init];
    [lineNum insertObject:@0 atIndex:0];
    //储存每行宽度
    NSMutableArray *lineWidth = [[NSMutableArray alloc] init];
    [lineWidth insertObject:@10.0 atIndex:0];
    //记录当前高度
    CGFloat verticalHeight = 10;
    //当前添加的行号
    int index = 0;
    
    for (int k = 0; k < self.dataList.count; k ++) {
        NSArray *array = self.dataList[k];
        
        //添加一个组头
        UICollectionViewLayoutAttributes *headerAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:[NSIndexPath indexPathForItem:0 inSection:k]];
        headerAttributes.frame = CGRectMake(0, verticalHeight + k*50, kScreenWidth, 50);
        [self.attributesArray addObject:headerAttributes];
        //相当于添加了一行
        [lineNum addObject:@1];
        [lineWidth addObject:@(kScreenWidth)];
        //添加组头,不需要计算组头的高度,单元格会自动适配到组头下面
        verticalHeight += 10;
        index ++;
        
        for (int i = 0; i < array.count; i ++) {
            UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:k]];
            //计算宽度
            CGFloat width = [self computerWidthWithString:array[i]];
            //计算位置
            CGFloat X;
            CGFloat Y;
            CGFloat indexWidth = [lineWidth[index] floatValue];  //当前行宽
            if ((indexWidth+width+10) <= self.collectionView.bounds.size.width) {
                //如果添加一个单元格,此行宽度还小于控件宽度,那就添加到此行
                X = [lineWidth[index] floatValue];
                Y = verticalHeight;
                lineNum[index] = @([lineNum[index] intValue]+1);
                lineWidth[index] = @([lineWidth[index] floatValue]+width+10);
            }else{
                //如果添加一个单元格,此行宽度大于控件宽度,那就另起一行
                index++;
                verticalHeight += 50;
                Y = verticalHeight;
                X = 10.0;
                [lineNum addObject:@(1)];
                [lineWidth addObject:@(width+10+10)];
            }
            
            attributes.frame = CGRectMake(X, Y, width, 40);
            [self.attributesArray addObject:attributes];
            
            //设置平均item属性
            int maxIndex = [self computerMAXlineWithArray:lineWidth];
            CGFloat aveWidth = ([lineWidth[maxIndex] floatValue]-[lineNum[maxIndex] intValue]*10-10)/[lineNum[maxIndex] intValue];
            self.itemSize = CGSizeMake(aveWidth, 40);
            
        }
    }
    
}

这里着重介绍这个计算方法
跟垂直瀑布流不同的是,水平瀑布流的计算方法是不断的将 item 往一行中放,直到这一行的宽度 + 新 item 的宽度已经超出了控件(collectionView)的宽度,那我们就另起一行。还要考虑的一个问题是,我们在这个水平瀑布流中添加了头视图。
头视图的 attributes 也是要添加入 collectionView 的 attributes 数组中的,这个头视图的位置我直接当做另起了一行,但是它的类型有所不同,它的类型是一个 UICollectionElementKindSectionHeader 。这个地方有一个坑,我调试了好久才调试好,单元格的位置是相对于这个头视图来定位的,也就是说,如果我们计算其他 item 的位置时加上了这个头视图的高度,那么实际效果就是这个 item 与头视图之间会多出一个头视图的距离。

2.最后还是返回它的 attributes 数组
//返回属性数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.attributesArray;
}

最后依旧放上我们可爱的 demo

demo 点这里!点这里!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容