自定义瀑布流

.h
//
// GBWaterFlowLayout.h
// UI15-CustomCollectionViewLayout
//
// Created by 郭宝 on 16/8/3.
// Copyright © 2016年 郭宝. All rights reserved.
//

import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@protocol GBWaterFlowLayoutDelegate <NSObject>
- (CGFloat)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
                    width:(CGFloat)width
 heightForItemAtIndexPath:(NSIndexPath *)indexpath;
@end

// 自定义布局, 继承于UICollectioniewLayout
// 切记不要继承UICollectioniewFlowLayout
@interface GBWaterFlowLayout : UICollectionViewLayout
// 列数Collection有多少列

@property (nonatomic, assign) NSInteger numberOfColumens;
@property (nonatomic, weak) id <GBWaterFlowLayoutDelegate> delegate;

@end
NS_ASSUME_NONNULL_END
.m
//
// GBWaterFlowLayout.m
// UI15-CustomCollectionViewLayout
//
// Created by 郭宝 on 16/8/3.
// Copyright © 2016年 郭宝. All rights reserved.
//

import "GBWaterFlowLayout.h"

@interface GBWaterFlowLayout ()

@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *attributesArray;
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, assign) CGFloat contentHeight;
// cell间 间距
@property (nonatomic, assign) CGFloat cellMargin;

@end

@implementation GBWaterFlowLayout

- (instancetype)init {
    self = [super init];
    if (self) {
        _attributesArray = [NSMutableArray array];// 数组初始化方法 赋初值
        _numberOfColumens = 2;
        _contentHeight = 0.0f;
        _cellMargin = 5.0f;
        // NSLog(@"%@", self.collectionView);// collectionView还没有
    }
    return self;
}
- (CGFloat)itemWidth {
    CGFloat allWidthMargin = (_numberOfColumens + 1) * _cellMargin;
    CGFloat noMarginWidth = CGRectGetWidth(self.collectionView.bounds) -allWidthMargin;
    return noMarginWidth / _numberOfColumens;
}

// 自定义Layout, 必须重写三个方法
// 计算每个item的大小

  • (void)prepareLayout {
    // 清空内容高度
    self.contentHeight = 0.0f;
// 清空layoutAttributes数组
    if (_attributesArray.count != 0) {
        [_attributesArray removeAllObjects];
    }
// 高度最小的列
    NSInteger column = 0;
// 存储每一列的高度
    NSMutableArray *columnOfHeightArray = [NSMutableArray array];
    for (int i = 0; i < _numberOfColumens; i++) {
        // 默认高度均为间距
        [columnOfHeightArray addObject:@(_cellMargin)];
    }
// NSLog(@"%lf", self.itemWidth);
// 加一层所有区遍历section
// 遍历collection中0区的所有item
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        // 创建系统需要的布局描述类
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        // 最小列的起始位置
        CGFloat x = (self.itemWidth + _cellMargin) * column + _cellMargin;
        // 高度数组中, 最小列对应的高度
        CGFloat y = [columnOfHeightArray[column] floatValue];
        // 根据列数, 计算出的宽度
        CGFloat width = self.itemWidth;
        // 通过代理方法计算得出
        CGFloat height = [self.delegate collectionView:self.collectionView layout:self width:self.itemWidth heightForItemAtIndexPath:index];
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [_attributesArray addObject:layoutAttributes];
        // 更新数组中对应最小列的高度
        columnOfHeightArray[column] = @([columnOfHeightArray[column]floatValue] +height + _cellMargin);
        // 整个内容的最大高度
        self.contentHeight = MAX(self.contentHeight, [columnOfHeightArray[column] floatValue]);
        for (int i = 0; i < columnOfHeightArray.count; i++) {
            CGFloat currentHeight = [columnOfHeightArray[column] floatValue];
            CGFloat height = [columnOfHeightArray[i] floatValue];
            if (currentHeight > height) {
                column = i;
            }
        }
    }
}

// 返回的是, 每个item对应的布局属性

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

// 负责CollectionView的滚动范围

- (CGSize)collectionViewContentSize {

    return CGSizeMake(0, self.contentHeight);
}

@end

vc.m
//
// ViewController.m
// UI15-CustomCollectionViewLayout
//
// Created by 郭宝 on 16/8/3.
// Copyright © 2016年 郭宝. All rights reserved.
//

#import "ViewController.h"
#import "CustomCollectionViewCell.h"
#import <AVFoundation/AVFoundation.h>
#import "GBWaterFlowLayout.h"
@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource, GBWaterFlowLayoutDelegate>
@property (nonatomic, strong) NSMutableArray<UIImage *> *imagesArray;
@property (nonatomic, assign) CGFloat itemWidth;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    // 设置背景图片
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Pattern"]];
    GBWaterFlowLayout *layout = [[GBWaterFlowLayout alloc] init];
    layout.delegate = self;
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor clearColor];// 设置背景色透明
    [self.view addSubview:collectionView];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [collectionView registerNib:[UINib nibWithNibName:@"CustomCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"reuse"];
    [self handleImages];
 
}
- (void)handleImages {
    _imagesArray = [NSMutableArray array];// 不初始化显示不出来
    for (int i = 0; i < 13; i++) {
        UIImage *image = [UIImage imageNamed:[@(i) description]];//先转成number再转成字符串
        [_imagesArray addObject:image];
    }
}

pragma mark - CollectionView waterLayout delegate

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
                    width:(CGFloat)width
 heightForItemAtIndexPath:(NSIndexPath *)indexpath {
    UIImage *image = _imagesArray[indexpath.row];
    CGRect boundingRect = CGRectMake(0, 0, width, CGFLOAT_MAX);//最大让它自己算
    CGRect imageCurrentRect = AVMakeRectWithAspectRatioInsideRect(image.size, boundingRect);
    return imageCurrentRect.size.height;
}

pragma mark - CollectionView datasource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _imagesArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    cell.myImageView.image = _imagesArray[indexPath.row];
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

推荐阅读更多精彩内容