03 - 一学就会的瀑布流

作者: 孟轲666 | 来源:发表于2017-07-26 09:34 被阅读51次

    前言:首先明白什么是瀑布流,就是类似于淘宝或者图片浏览那样式的,有的图片高,有的图片矮,不是九宫格,更不是基于流水布局的collectionview。我们可以自定义布局,使用collectionview不用关心循环利用的问题。

    • 先看下效果图:


    好,我们正式开始:
    1.首先要创建一个布局,(已经确定流水布局不能满足我们的需求了)

    Snip20170726_2.png

    2.利用我们的布局进行collectionview的创建:

    #import "ViewController.h"
    #import "MKWaterFlowLayout.h"
    @interface ViewController ()<UICollectionViewDataSource>
    
    @end
    
    @implementation ViewController
    static NSString * const MKShop = @"shop";
    - (void)viewDidLoad {
        [super viewDidLoad];
        MKWaterFlowLayout * layout = [[MKWaterFlowLayout alloc]init];
        
        UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        
        collectionView.dataSource = self;
        [self.view addSubview:collectionView];
        
        //注册
        [collectionView registerClass:[UICollectionViewCell class]forCellWithReuseIdentifier:MKShop];
    }
    #pragma mark - 数据源方法
    -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
        return 50;
    }
    
    - (UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
        UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:MKShop forIndexPath:indexPath];
        cell.backgroundColor = [UIColor orangeColor];
        NSInteger tag = 10;
        UILabel * label = (UILabel*)[cell.contentView viewWithTag:tag];
        if (label == nil) {
            label = [[UILabel alloc]init];
            label.tag = tag;
            [cell.contentView addSubview:label];
        }
        label.text = [NSString stringWithFormat:@"%ld",indexPath.item];
        [label sizeToFit];
        
        return cell;
    }
    
    
    • 这个时候如果你运行的话是不会有内容显示的,如果把继承换成流水布局的话,会默认显示内容。

    3.接着我们去配置我们自己的布局,继承自UICollectionViewLayout,首先要实现4个方法:

    //初始化
     //这个方法记得调super
    - (void)prepareLayout;
    
    //决定cell的排布
    - (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect;
    
    //返回indexPath位置cell对应的布局属性
    -(UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
    
    //能滚动,就得有滚动的范围
    - (CGSize)collectionViewContentSize;
    

    4.接下来就是实现上面那4个方法了,在正式开始之前,先说明一点,就是瀑布流当第一行排满排第二行的时候,不是按顺序先拍左面然后依次排列的,而是看那列的cell最短,然后先排那列:

    Snip20170726_4.png
    • 下面是具体的实现代码,因为注释写的比较详细,这里就不赘述了
    /** 默认的列数 */
    static const CGFloat MKDefaultColumnCount = 3;
    /** 每一列之间的间距 */
    static const CGFloat MKDefaultColumnMargin = 10;
    /** 每一行之间的间距 */
    static const CGFloat MKDefaultRowMargin = 10;
    /**
     * 边缘间距
     *(之所以用{}来写,是因为   UIEdgeInsetsMake(<#CGFloat top#>, <#CGFloat left#>, <#CGFloat bottom#>, <#CGFloat right#>)函数调用,程序运行的时候才能调用,而static const(静态变量)是在编译阶段就需要确定的,所以这里不能写UIEdgeInsetsMake)
     */
    static const UIEdgeInsets MKEdgeInsets = {10,10,10,10};
    
    @interface MKWaterFlowLayout()
      //创建一个数组(存放所有cell的布局属性)
    @property (nonatomic,strong) NSMutableArray * array;
    /** 存放所有列的最大高度 */
    @property (nonatomic, strong) NSMutableArray * columnHeight;
    
    @end
    @implementation MKWaterFlowLayout
    - (NSMutableArray *)columnHeight
    {
        if (!_columnHeight) {
            _columnHeight = [NSMutableArray array];
        }
        
        return _columnHeight;
    }
    
    
    
    - (NSMutableArray *)array{
        if (!_array) {
            _array = [NSMutableArray array];
        }
     
        return _array;
    }
    /**
     *  初始化
     */
    - (void)prepareLayout{
        //这个方法记得调super
        [super prepareLayout];
        
        //先清除以前计算的所有高度,然后给数组中原始赋值,否则会出现数组越界的问题,因为一开始数组是空的,
        [self.columnHeight removeAllObjects];;
        for (NSInteger i = 0; i <MKDefaultColumnCount; i ++) {
            [self.columnHeight addObject:@(MKEdgeInsets.top)];
        }
        
      //清除之前的布局属性,防止刷新的时候不断往数组中加东西,也可以直接清除  self.array = nill;
        [self.array removeAllObjects];
        
        //开始创建每一个cell对应的布局属性
        NSInteger count = [self.collectionView numberOfItemsInSection:0];
        for (NSInteger i = 0; i < count; i ++) {
            //创建位置
            NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            UICollectionViewLayoutAttributes * attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
            
            [self.array addObject:attrs];
        }
    }
    /**
     * 决定cell的排布
     */
    - (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{
    
        return self.array;
    }
    /**
     * 返回indexPath位置cell对应的布局属性
     */
    - (UICollectionViewLayoutAttributes*)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
        //创建布局属性
        UICollectionViewLayoutAttributes * attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        //设置布局属性的frame
        CGFloat collectionW = self.collectionView.frame.size.width;
        CGFloat w = (collectionW - MKEdgeInsets.left - MKEdgeInsets.right - (MKDefaultColumnCount -1)*MKDefaultColumnMargin)/MKDefaultColumnCount;
        XMGShop * shop = self.shops[indexPath.item];
        CGFloat h = w * shop.h/shop.w;
        
        //找出高度最短的那一列
    //    __block NSInteger destColumn = 0;
    //    //block中不能修改外面的变量,要想修改,必须前面加__block
    //    __block CGFloat minColumnHeight = MAXFLOAT;
    //    [self.columnHeight enumerateObjectsUsingBlock:^(NSNumber * columnHeightNumber, NSUInteger idx, BOOL *stop) {
    //        CGFloat columnHeight = columnHeightNumber.doubleValue;
    //        if (minColumnHeight > columnHeight) {
    //            minColumnHeight = columnHeight;
    //            destColumn = idx;
    //        }
    //    }];
        
        
        NSInteger destColumn = 0;
        //block中不能修改外面的变量,要想修改,必须前面加__block
         CGFloat minColumnHeight = [self.columnHeight[0]doubleValue];
        for (NSInteger i = 1; i <MKDefaultColumnCount; i ++) {
            CGFloat columnHeight = [self.columnHeight[i] doubleValue];
            if (minColumnHeight >columnHeight) {
                minColumnHeight = columnHeight;
                destColumn = i;
            }
        }
        CGFloat x = MKEdgeInsets.left + destColumn * (w + MKDefaultColumnMargin);
        CGFloat y = minColumnHeight;
        if (y != MKEdgeInsets.top) {
            y = minColumnHeight + MKDefaultRowMargin;
        }
        
         attrs.frame = CGRectMake(x,y,w,h);
        
        //更新最短那列的高度
        self.columnHeight[destColumn] = @(CGRectGetMaxY(attrs.frame));
     
       
        
        return attrs;
    }
    //能滚动,就得有滚动的范围
    - (CGSize)collectionViewContentSize{
        CGFloat maxColumnHeight = [self.columnHeight[0]doubleValue];
        for (NSInteger i = 1; i <MKDefaultColumnCount; i ++) {
            CGFloat columnHeight = [self.columnHeight[i] doubleValue];
            if (maxColumnHeight < columnHeight) {
                maxColumnHeight = columnHeight;
                
            }
        }
    
        return CGSizeMake(0, maxColumnHeight + MKEdgeInsets.bottom);
    }
    
    

    PS:这里有一点写的不好,就是对模型的依赖太强,代码的可移植性不强,如果想要写成一个瀑布流的第三方框架,不应该直接把模型传进去,可以模仿苹果官方的tableview,设置一个代理去传值。

    更新

    #import <UIKit/UIKit.h>
    
    @class MKWaterFlowLayout;
    @protocol MKWaterFlowLayoutDelegate <NSObject>;
    @required
    - (CGFloat)waterFlowLayout:(MKWaterFlowLayout *)waterFlowLayout heightForRowAtIndexPath:(NSInteger)indexPath withWidth:(CGFloat)width;
    
    @end
    @interface MKWaterFlowLayout : UICollectionViewLayout
    @property (nonatomic,weak) id<MKWaterFlowLayoutDelegate> delegate;
    @end
    
    

    相关文章

      网友评论

        本文标题:03 - 一学就会的瀑布流

        本文链接:https://www.haomeiwen.com/subject/tudnkxtx.html