美文网首页
瀑布流的简单实现

瀑布流的简单实现

作者: 请叫我魔法师 | 来源:发表于2017-10-19 16:36 被阅读0次

很简答的瀑布流,用collectionview实现cell高度不一致的情况下的排列。
主要就是自定义layout。
先看效果:


AAA-BBB.gif

自定义layout必须实现下面5个方法:

//完成布局前的初始工作
-(void)prepareLayout;

//collectionView的内容尺寸
-(CGSize)collectionViewContentSize;

//为每个item设置属性(被下面的那个方法调用)
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;

//获取制定范围的所有item的属性(调用的是上面的那个方法,存到数组)
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;

//在collectionView的bounds发生改变的时候刷新布局
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;

一、原理

layout文件负责collectionview的布局。所以在layout中计算完每个cell的坐标信息,就实现了瀑布流。所以瀑布流的重点是计算每个cell的位置信息。
cell的顺序:从左上角是第0个cell,接着要放置第1个,这个怎么放?为了把屏幕铺满,只能放到最短的那列里。接着放第2个cell,也只放到最短的那一列里。以此类推,直到数据源里的最后一个。保证每次新增的cell放在最短的那一列。

经过上面简单的分析,cell的顺序很重要。每次存放cell,都需要判断最短是哪一列,然后再放。如图:


排列顺序.png

直接上代码:
layout的h文件

#import <UIKit/UIKit.h>
//继承自UICollectionViewFlowLayout
@interface PhotoLayout : UICollectionViewFlowLayout
//需要显示几列
@property (nonatomic, assign) NSInteger lines;
//左右cell的间距
@property (nonatomic, assign) CGFloat leftRSpace;
//上下cell的间距
@property (nonatomic, assign) CGFloat topBSpace;
//存放高度的数组,可以根据实际需求处理
@property (nonatomic, strong) NSMutableArray *heightArr; 
@end

m文件:为了代码看着连贯,直接全部复制了。

#import "PhotoLayout.h"
#define SCREENW [UIScreen mainScreen].bounds.size.width

@interface PhotoLayout ()

@property (nonatomic, strong) NSMutableArray *attrsArray; //cell的属性数组,存放cell位置信息

@property (nonatomic, strong) NSMutableArray *columnHeights;//高度数组,存放每列高度。有几列这个数组就包含几个对象
@property(nonatomic,assign)CGFloat cellWidth; //cell的宽度

@end


@implementation PhotoLayout

//布局的准备
- (void)prepareLayout {
    
    [super prepareLayout];
    
//    清空cell位置信息数据和高度数组
    [self.attrsArray removeAllObjects];
    [self.columnHeights removeAllObjects];
    
//    计算cell的宽度
    self.cellWidth = (SCREENW - self.sectionInset.left - self.sectionInset.right - (self.lines-1)*self.leftRSpace ) * 0.5;
    
//    存放最原始高度,这个时候还没有cell的高度,其实就是section的上边距
    for (int i = 0; i < self.lines; i ++) {
        [self.columnHeights addObject:@(self.sectionInset.top)];
    }

//    这里没什么可注释的,一看就明白。循环计算各个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.attrsArray addObject:attrs];
    }
}

//cell属性数组的懒加载
- (NSMutableArray *)attrsArray{
    if (_attrsArray == nil) {
        _attrsArray = [[NSMutableArray alloc] init];
    }
    return _attrsArray;
}

//高度数组的懒加载。根据自己需求,可以不用数组一次性计算所有数据的高度。也可以实时计算高度。
- (NSMutableArray *)columnHeights {
    if (_columnHeights == nil) {
        _columnHeights = [[NSMutableArray alloc] init];
    }
    return _columnHeights;
}

//计算每个cell的属性信息
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
//    初始化属性
    UICollectionViewLayoutAttributes *atts = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
//    根据高度数组,循环一次,找出最短的那一列。就可以确定这个cell放到哪一列了。
//    取出第0个元素的高度
    NSInteger columnIndex = 0;
    CGFloat minHeight = [self.columnHeights[0] floatValue];
    for (NSInteger i = 1; i < self.lines; i ++) {
//        根据第0个高度,和其他高度对比
        CGFloat cellHeight = [self.columnHeights[i] floatValue];
//        确定最短的那个高度是多少,并记录是哪一列的高度
        if (minHeight > cellHeight) {
            minHeight = cellHeight;
            columnIndex = i;
        }
    }

//    根据section边距,cell左右间隙和上面确定的cell所在的列,计算出cell的x坐标
    CGFloat cellX = self.sectionInset.left + columnIndex * (self.leftRSpace + self.cellWidth);
    
//    根据确定的最短列的高度和cell的上线间隙,确定cell的y坐标
    CGFloat cellY = minHeight + self.topBSpace;
    
//    根据高度数组,确定cell的高度
//    --PS根据自己需求,可以不用数组一次性计算所有数据的高度。也可以实时计算高度。
    CGFloat cellH = [self.heightArr[indexPath.row] floatValue];
//    最后确定cell的frame
    atts.frame = CGRectMake(cellX, cellY, self.cellWidth, cellH);

//    由于新增了一个cell,更新这一列的高度
    self.columnHeights[columnIndex] = @(minHeight + self.topBSpace + cellH);
    
    return atts;
}


//通过调用上面的方法,把所有cell的属性方法一个数组里
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    
    return self.attrsArray;
}

//实时更新collectionview的contentsize,由于每次屏幕上新出现cell就重新布局方法,contentsize也会变化
- (CGSize)collectionViewContentSize{
    
//    还是先取出第0列的高度
    NSNumber *longestNum = self.columnHeights[0];
    CGFloat longest = [longestNum floatValue];

//    循环一下哈,得到最长的高度。为了显示完整,所以contentsize是有最长的列的决定的。
    for (NSInteger i = 1; i < self.columnHeights.count; i++) {
        NSNumber* rolHeight = self.columnHeights[i];
        if(longest < rolHeight.floatValue){
            longest = rolHeight.floatValue;
        }
    }
    
//    最长的列的高度,最后再加上section的底部间距
    return CGSizeMake(self.collectionView.frame.size.width, longest + self.sectionInset.bottom);
}

//在collectionView的bounds发生改变的时候刷新布局
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return !CGRectEqualToRect(self.collectionView.bounds, newBounds);
}

@end

二、使用

以上layout文件全局说完了。在控制器的调用就简单多了。

//    layout对象最好写成全局变量,实际开发中,数据是在网络请求后得到,所以高度的确定也在网络请求后,
    self.layout = [[PhotoLayout alloc] init];
//    为了代码的重复使用方便,这些数据由控制器决定。
    self.layout.sectionInset = UIEdgeInsetsMake(0, 25, 0, 25);
    self.layout.lines = 2;
    self.layout.leftRSpace = 15;
    self.layout.topBSpace = 15;
    
    self.layout.heightArr = [[NSMutableArray alloc] init];
    
    self.collView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.layout];
    self.collView.alwaysBounceVertical = YES;
    self.collView.backgroundColor = [UIColor whiteColor];
    self.collView.delegate = self;
    self.collView.dataSource = self;
    [self.view addSubview:self.collView];
//网络请求
- (void)loadNetData {
    for (int i = 0; i < 50; i++) {
        //模拟数据,得到不一样的高度而已。
        if (i % 3 == 0) {
            [self.layout.heightArr addObject:@(150)];
        }else{
            [self.layout.heightArr addObject:@(100)];
        }
    }
    [self.collView reloadData];
}

OVER!

相关文章

网友评论

      本文标题:瀑布流的简单实现

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