UICollectionView 瀑布流的使用

缘由:最近项目中瀑布流遇到的机率相当高,想想以前就是直接用CHTCollectionViewWaterfallLayout,并没有详细去看里面的实现,回来后自己就跟着写一遍,特此记录。

一、了解原生UICollectionViewLayout的几个方法
#pragma mark - 准备布局
- (void)prepareLayout;
#pragma mark - 当尺寸有所变化时,重新刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds; 
#pragma mark - 处理所有的Item的layoutAttributes
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
#pragma mark - 处理单个的Item的layoutAttributes
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
#pragma mark - CollectionView的滚动范围
- (CGSize)collectionViewContentSize;

以上几个方法,都是需要重写父类的方法,实现瀑布流布局。

二、实现上述几个方法的实际情况

此处下面代码转载UICollectionView详解:瀑布流, 写的很清楚,然后我们在使用 UICollectionView 的时候只要将
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout 中的 layout 换成自己的自定义的就 OK,同时不忘记使用其代理的实现就让瀑布流出来啦。

#import <UIKit/UIKit.h>

@protocol PQWaterFlowLayoutDelegate;

@interface PQWaterFlowLayout : UICollectionViewLayout

// cell的列间距
@property (nonatomic, assign) CGFloat columnMargin;
// cell的行间距
@property (nonatomic, assign) CGFloat rowMargin;
// cell的top,right,bottom,left间距
@property (nonatomic, assign) UIEdgeInsets insets;
// 显示多少列
@property (nonatomic, assign) NSInteger count;
// delegate
@property (nonatomic, weak) id <PQWaterFlowLayoutDelegate> delegate;

@end

@protocol PQWaterFlowLayoutDelegate <NSObject>

/*通过代理获得每个cell的高度(之所以用代理取得高度的值,就是为了解耦,这里定义的LFWaterFlowLayout不依赖与任务模型数据)*/
- (CGFloat)waterFlowLayout:(PQWaterFlowLayout *)waterFlowLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath;

@end
#import "PQWaterFlowLayout.h"

@interface PQWaterFlowLayout ()

/* Key: 第几列; Value: 保存每列的cell的底部y值 */
@property (nonatomic,strong) NSMutableDictionary *cellInfo;

@end

@implementation PQWaterFlowLayout

#pragma mark - 初始化属性
- (instancetype)init {
    self = [super init];
    if (self) {
        self.columnMargin = 10;
        self.rowMargin = 10;
        self.insets = UIEdgeInsetsMake(10, 10, 10, 10);
        self.count = 2;
    }
    return self;
}

- (NSMutableDictionary *)cellInfo {
    if (!_cellInfo) {
        _cellInfo = [NSMutableDictionary dictionary];
    }
    return _cellInfo;
}


#pragma mark - 当尺寸有所变化时,重新刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}
#pragma mark - 准备布局
- (void)prepareLayout {
    [super prepareLayout];
    
    for (int i=0; i<self.count; i++) {
        NSString *index = [NSString stringWithFormat:@"%d",i];
        self.cellInfo[index] = @(self.insets.top);
    }
}

#pragma mark - 处理所有的Item的layoutAttributes
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    // 每次重新布局之前,先清除掉以前的数据(因为屏幕滚动的时候也会调用)
    __weak typeof (self) wSelf = self;
    [self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *minY, BOOL *stop) {
        wSelf.cellInfo[columnIndex] = @(wSelf.insets.top);
    }];
    
    
    NSMutableArray *array = [NSMutableArray array];
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    for (int i=0; i<count; i++) {
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        [array addObject:attrs];
    }
    
    return array;
}

#pragma mark - 处理单个的Item的layoutAttributes
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 获取cell底部Y值最小的列
    __block NSString *minYForColumn = @"0";
    __weak typeof (self) wSelf = self;
    [self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *minY, BOOL *stop) {
        if ([minY floatValue] < [wSelf.cellInfo[minYForColumn] floatValue]) {
            minYForColumn = columnIndex;
        }
    }];
    
    CGFloat width = (self.collectionView.frame.size.width - self.insets.left - self.insets.right - self.columnMargin * (self.count - 1)) / self.count;
    CGFloat height = [self.delegate waterFlowLayout:self heightForWidth:width atIndexPath:indexPath];
    CGFloat x = self.insets.left + (width + self.columnMargin) * [minYForColumn integerValue];
    CGFloat y = self.rowMargin + [self.cellInfo[minYForColumn] floatValue];
    
    self.cellInfo[minYForColumn] = @(y + height);
    
    // 创建属性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.frame = CGRectMake(x, y, width, height);
    return attrs;
}

#pragma mark - CollectionView的滚动范围
- (CGSize)collectionViewContentSize {
    CGFloat width = self.collectionView.frame.size.width;
    
    __block CGFloat maxY = 0;
    [self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *itemMaxY, BOOL *stop) {
        if ([itemMaxY floatValue] > maxY) {
            maxY = [itemMaxY floatValue];
        }
    }];
    
    return CGSizeMake(width, maxY + self.insets.bottom);
}


@end

三、具体思路的实现

3-1、确定滚动方向、默认列数、行间距、列间距

self.columnMargin = 10;
self.rowMargin = 10;
self.insets = UIEdgeInsetsMake(10, 10, 10, 10);
self.count = 2;

3-2、可以提供一个数组(记录当前每一列的最大Y值),假如count,我们就提供一个count个元素的数组,记录所有布局属性。

 for (int i=0; i<self.count; i++) {
        NSString *index = [NSString stringWithFormat:@"%d",i];
        self.cellInfo[index] = @(self.insets.top);
 }

3-3、在layoutAttributesForElementsInRect:方法(返回所有元素的布局属性数组 ),并保存。

__weak typeof (self) wSelf = self;
[self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *minY, BOOL *stop) {
    wSelf.cellInfo[columnIndex] = @(wSelf.insets.top);
}];
NSMutableArray *array = [NSMutableArray array];
NSInteger count = [self.collectionView numberOfItemsInSection:0];

for (int i=0; i<count; i++) {
    UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    [array addObject:attrs];
}

return array;

3-4、我们可以在layoutAttributesForItemAtIndexPath: 方法: 来调整 Cell的布局属性 , 指定Cell的 frame, 这个就是最核心的确定了frame

CGFloat width = (self.collectionView.frame.size.width - self.insets.left - self.insets.right - self.columnMargin * (self.count - 1)) / self.count;
CGFloat height = [self.delegate waterFlowLayout:self heightForWidth:width atIndexPath:indexPath];
CGFloat x = self.insets.left + (width + self.columnMargin) * [minYForColumn integerValue];
CGFloat y = self.rowMargin + [self.cellInfo[minYForColumn] floatValue];

self.cellInfo[minYForColumn] = @(y + height);

// 创建属性
UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attrs.frame = CGRectMake(x, y, width, height);

3-5、设置collectionView的contentSize,让其正常滚动。

CGFloat width = self.collectionView.frame.size.width;
__block CGFloat maxY = 0;
[self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *itemMaxY, BOOL *stop) {
    if ([itemMaxY floatValue] > maxY) {
        maxY = [itemMaxY floatValue];
    }
}];

return CGSizeMake(width, maxY + self.insets.bottom);

当然,我们平常用的时候,只要用CHTCollectionViewWaterfallLayout这个就 OK 了,比较完善,而且项目一直在更新中,强烈推荐。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容