用UICollectionView实现瀑布流

一 设置UICollectionView

新建一个项目,直接在storyboard当中拖入一个UICollectionView并与控制器关联.

1.设置属性

@property(weak,nonatomic) IBOutlet UICollectionView*ldCollectionView;

2.关联Delegate和DataSource

_ldCollectionView.delegate=self;
_ldCollectionView.dataSource=self;

3.注册class

UICollectionView与UITableView不同的一点,UICollectionView只能通过

- (void)registerClass:(nullableClass)cellClass forCellWithReuseIdentifier:(NSString*)identifier;
- (void)registerNib:(nullableUINib*)nib forCellWithReuseIdentifier:(NSString*)identifier;

这两个方法来注册UICollectionViewCell。
这里我直接注册UICollectionViewCell的类

[_ldCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:ldCollectionViewCell];

4.实现DataSource方法

使用UICollectionView必须实现DataSource里的这两个方法

- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section;
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:   调用注册的Class需要用这个方法获取
-(UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath;

二 实现collectionViewLayout

1.设置collectionViewLayout的方法

需要实现瀑布流的主要步骤在于设置UICollectionView的collectionViewLayout(默认为UICollectionViewFlowLayout),设置该属性可通过以下方法。

//代码创建UICollectionView时直接传入layout。                                                                       - (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout*)layout;
//实例化UICollectionView后设置该属性
@property(nonatomic,strong)UICollectionViewLayout*collectionViewLayout;
//变换layout并决定是否显示动画。
- (void)setCollectionViewLayout:(UICollectionViewLayout*)layout animated:(BOOL)animated;
- (void)setCollectionViewLayout:(UICollectionViewLayout*)layout animated:(BOOL)animated completion:(void(^__nullable)(BOOLfinished))completion;

2.创建自己的UICollectionViewLayout

创建的UICollectionViewLayout既可以继承自UICollectionViewLayout也可以继承自UICollectionViewFlowLayout.继承这两个的主要区别在于这两个方法(目前我发现的区别):

- (CGSize)collectionViewContentSize;
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect

第一个方法的主要作用是返回collectionView的content大小。如果继承自UICollectionViewLayout而没有实现该方法,那么collectionView只显示一个屏幕的内容,并且不能滚动。
如果继承自UICollectionViewFlowLayout而不实现该方法,collectionview可以滚动,但滚动的范围为UICollectionViewFlowLayout布局时滚动的范围。并不会因为布局中设置高度不一样的item而改变。
第二个方法如果是继承于UICollectionViewFlowLayout则调用[super layoutAttributesForElementsInRect:(CGRect)rect]会返回已经缓存的数组。而继承UICollectionViewLayout则会直接返回nil

2.1 设置UICollectionViewLayout

UICollectionViewLayout中为Subclass提供的方法需要实现以下几个

- (void)prepareLayout;
//告知collection它的contentSize。
- (CGSize)collectionViewContentSize;
//每次可见范围改变时便调用该方法。返回所有可见内容的布局(包括headerView等),rect为collection可见范围。
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;

实现瀑布流,每次将新的item放到所有列中最短的那一列下面,这样才不会导致瀑布流一列比其它长太多。

按顺序添加item
按最短一列添加item

.h文件

#import <UIKit/UIKit.h>
typedef CGFloat(^GetHeightBlock)(NSIndexPath * _Nonnull index);//获取每个item的高度的block

@interface LDWaterfallStreamCollectionViewLayout : UICollectionViewLayout

@property (nonnull,nonatomic,copy)NSNumber *itemCount;//一行显示几列,默认2;

@property (nonnull,nonatomic,copy)GetHeightBlock getHeightBlock;

@end

.m文件

#import "LDWaterfallStreamCollectionViewLayout.h"

#define itemMargin 5.0f

@interface LDWaterfallStreamCollectionViewLayout()
@property (nonatomic,strong)NSMutableArray *attrArray;//保存attrArray,避免每次滑动都重新遍历获取attr.
@property (nonatomic,strong)NSMutableArray *minHeightArray;//保存每列的高度。
@property (nonnull,nonatomic,copy)NSNumber *itemWidth;//行宽,默认屏幕一半少1.5个margin;
@end

初始化数据

//懒加载,第一次调用需用self.
-(NSMutableArray *)attrArray{
    if (!_attrArray) {
        _attrArray=[[NSMutableArray alloc]init];
    }
    return _attrArray;
}
-(NSNumber *)itemCount{
    if (!_itemCount) {
        _itemCount=@2;
    }
    return _itemCount;
}
-(NSNumber *)itemWidth{
    if (!_itemWidth) {
         _itemWidth=[NSNumber numberWithFloat:(self.collectionView.frame.size.width-([_itemCount intValue]+1)*itemMargin)/[_itemCount intValue]];
    }
    return _itemWidth;
}
//初始化保存每列高度的数组
-(NSMutableArray *)minHeightArray{
    //初始化为0
    if (!_minHeightArray) {
        NSMutableArray * array = [NSMutableArray array];
        for(int i =0;i<[self.itemCount intValue];i++){
            [array addObject:@0];
        }
        _minHeightArray = [array mutableCopy];
    }
    return _minHeightArray;
}

//继承UICollectionViewLayout需要告知contentSize
-(CGSize)collectionViewContentSize{
    NSNumber *max=self.minHeightArray[0];
    for (int i=0;i<[self.itemCount intValue]; i++) {
        if ([max compare:self.minHeightArray[i]]==NSOrderedAscending) {
            //[A compare:B]==NSOrderedAscending ->A<B
            max=self.minHeightArray[i];
        }
    }
    return CGSizeMake(self.collectionView.frame.size.width, [max floatValue]);
}

-(void)saveattrArray{
    //每次都会调用prepareLayout方法,所以要先把两个数组清空。 
    [self.attrArray removeAllObjects];
    self.minHeightArray = nil;
    NSInteger sectionCount=[self.collectionView numberOfSections];
    for (int i  = 0;i<sectionCount; i++) {
        NSInteger itemCount=[self.collectionView numberOfItemsInSection:i];
        for (int k = 0; k<itemCount;k++) {
            [self.attrArray addObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:k inSection:i]]];
        }
    }
}

- (void)prepareLayout{
    [super prepareLayout];
    [self saveattrArray];
}

返回布局

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.attrArray;
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *attr=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    CGFloat height=self.getHeightBlock(indexPath);//传值在主文件中实现该block
    NSNumber *min=self.minHeightArray[0];
    NSInteger minNumber=0;
   //获取数组中最小的一个数的位置
    for (int i=0;i<[self.itemCount intValue]; i++) {
        if ([min compare:self.minHeightArray[i]]==NSOrderedDescending) {
            min=self.minHeightArray[i];
            minNumber=i;
        }
    }
   //设置该item的frame
    attr.frame=CGRectMake(minNumber*[self.itemWidth floatValue]+itemMargin*(minNumber+1),[min floatValue],[self.itemWidth floatValue], height);
   //将数组中的数加此item的高度再加item间隔,重新保存。
    self.minHeightArray[minNumber]=[NSNumber numberWithFloat:([min floatValue]+itemMargin)+height];
    return attr;
}

在主文件中实现block

    LDWaterfallStreamCollectionViewLayout *layout=[[LDWaterfallStreamCollectionViewLayout alloc]init];
    [layout setGetHeightBlock:^CGFloat(NSIndexPath *index){
        return [self.array[index.item] floatValue];//该数组为保存你高度的数组。
    }];
    _ldCollectionView.collectionViewLayout=layout;

3.关于HeaderView和FooterView

在UICollectionView中headerView和item一样,都需要通过注册来实现。

//UIKIT_EXTERN NSString *const UICollectionElementKindSectionHeader NS_AVAILABLE_IOS(6_0);
//UIKIT_EXTERN NSString *const UICollectionElementKindSectionFooter NS_AVAILABLE_IOS(6_0);  
 [_ldCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:ldSectionHeader];

如果继承UICollectionViewFlowLayout则可以实现UICollectionViewDelegateFlowLayout里的两个方法

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;

而继承自UICollectionViewLayout的则需要在自己的layout文件中实现:

- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath;

两种形式都需要在主文件中实现

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

注意:如果自己实现的layout没有主动调用

- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath;

这个方法,则不会进入到获取UICollectionReusableView的阶段。
以下是我理解的该行为的调用顺序:

调用流程

所以要调用哪个类型的view的size方法(head或者foot)一定要注册该类型的类,不然会crash(缓冲池中没有注册该类型的类)
注:UICollectionViewFlowLayout的headerview宽度固定为collectionview的宽度

需要有headerview可以更改方法

-(void)saveattrArray{
    [self.attrArray removeAllObjects];
    self.minHeightArray = nil;
    NSInteger sectionCount=[self.collectionView numberOfSections];
    for (int i  = 0;i<sectionCount; i++) {
        NSInteger itemCount=[self.collectionView numberOfItemsInSection:i];
        for (int k = 0; k<itemCount;k++) {
            [self.attrArray addObject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:k inSection:i]]];
        }
        //加入这一行
        [self.attrArray addObject:[self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter atIndexPath:[NSIndexPath indexPathForItem:0 inSection:i]]];
    }
//实现这个方法
-(UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes *attr=[UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:elementKind withIndexPath:indexPath];
    attr.frame=CGRectMake(0, 0,200, self.collectionView.frame.size.height);
    return attr;
}

自定义layout中的所有(包括item和header等)的frame都是相对于collection,所以要自定义layout的时候需要根据section以及是否有headerview来偏移,这些都是需要自己计算的,而我给出的代码是一个section的,并没有计算多个section以及拥有headerview时的偏移。

效果图.gif

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

推荐阅读更多精彩内容