瀑布流是新聞、電商類 App 裡極常見的版面形式。要實現它,關鍵在於理解 UICollectionView 的佈局機制,並動手改寫它的佈局方式。
在動手之前,先掌握幾個重點:

如圖所示,模擬器上呈現的是一格格方塊,它們排列得整整齊齊,卻也顯得單調呆板。我們所要做的瀑布流,正是要在保留規律的前提下打破這種整齊,讓每個 cell 高度不一,如同流水般自然錯落。
既然 UICollectionView 的大部分操作都在 FlowLayout 上,那麼實現瀑布流的核心,就是改寫它的格局部署邏輯。動手前先理清思路:

先來看控制器部分,它負責配置 collectionView 與數據源:
// ViewController.m // CX-瀑布流 UICollectionView 實現
#import "ViewController.h"
#import "CXCollectionViewCell.h"
#import "CXCollectionViewLayout.h"
static NSString * identifier = @"cellID";
@interface ViewController ()<UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView * collectionView;
@end
@implementation ViewController
#pragma mark - <懶加載>
- (UICollectionView *)collectionView {
if (!_collectionView) {
//初始化自定義的 flowLayout
CXCollectionViewLayout * flowLayout = [[CXCollectionViewLayout alloc]init];
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
_collectionView.dataSource = self;
[_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CXCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:identifier];
}
return _collectionView;
}
#pragma mark - <life>
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.collectionView];
}
#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 100;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
CXCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
cell.label.text = [NSString stringWithFormat:@"%zd",indexPath.item];
cell.backgroundColor = [UIColor orangeColor];
return cell;
}
@end
真正的關鍵在自定義的 Layout。它需要重寫準備佈局、返回佈局屬性與計算內容尺寸等方法:
// CXCollectionViewLayout.m // CX-瀑布流 UICollectionView 實現
#import "CXCollectionViewLayout.h"
static NSInteger CXcolumnCount = 3; //列數
static UIEdgeInsets CXdefaultEdgeInsets = {20,15,10,15}; //內邊距
static NSInteger CXcolumnMagin = 10; //列間距
static NSInteger CXrowMagin = 10; //行間距
@interface CXCollectionViewLayout ()
@property (nonatomic, strong) NSMutableArray * CXattrsArray; //所有 cell 的佈局屬性
@property (nonatomic, strong) NSMutableArray * CXcolumnHeights; //各列高度
@end
@implementation CXCollectionViewLayout
- (NSMutableArray *)CXattrsArray{
if (!_CXattrsArray) { _CXattrsArray = [NSMutableArray array]; }
return _CXattrsArray;
}
- (NSMutableArray *)CXcolumnHeights{
if (!_CXcolumnHeights) { _CXcolumnHeights = [NSMutableArray array]; }
return _CXcolumnHeights;
}
#pragma mark - <准備佈局>
- (void) prepareLayout{
[super prepareLayout];
//每次佈局前清空之前存儲的屬性
[self.CXcolumnHeights removeAllObjects];
[self.CXattrsArray removeAllObjects];
//為第一行各列初始化高度
for (NSInteger i = 0; i < CXcolumnCount; i ++) {
[self.CXcolumnHeights addObject:@(CXdefaultEdgeInsets.top)];
}
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (NSInteger i = 0; i < count; i ++) {
NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
UICollectionViewLayoutAttributes * attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
[self.CXattrsArray addObject:attributes];
}
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
return self.CXattrsArray;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewLayoutAttributes * CXattributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGFloat collectionViewWidth = self.collectionView.frame.size.width;
CGFloat width;
CGFloat height;
CGFloat X;
CGFloat Y;
width = (collectionViewWidth - CXdefaultEdgeInsets.left - CXdefaultEdgeInsets.right - (CXcolumnCount - 1) * CXcolumnMagin) / CXcolumnCount;
//實際開發中 height 由數據決定,此處用 100~150 的隨機數演示原理
height = 100 + arc4random_uniform(50);
//找出當前最矮的一列
NSInteger tempColumn = 0;
CGFloat minColumnHeight = [self.CXcolumnHeights[0] doubleValue];
for (NSInteger i = 1; i < CXcolumnCount; i ++) {
if (minColumnHeight > [self.CXcolumnHeights[i] doubleValue]) {
minColumnHeight = [self.CXcolumnHeights[i] doubleValue];
tempColumn = i;
}
}
X = CXdefaultEdgeInsets.left + (width + CXcolumnMagin) * tempColumn;
Y = minColumnHeight;
if (Y != CXdefaultEdgeInsets.top) {
Y += CXrowMagin;
}
CXattributes.frame = CGRectMake(X, Y, width, height);
//更新最矮那一列的高度
self.CXcolumnHeights[tempColumn] = @(CGRectGetMaxY(CXattributes.frame));
return CXattributes;
}
- (CGSize)collectionViewContentSize{
CGFloat maxColumnHeight = [self.CXcolumnHeights[0] doubleValue];
for (NSInteger i = 1; i < CXcolumnCount; i++) {
CGFloat columnHeight = [self.CXcolumnHeights[i] doubleValue];
if (maxColumnHeight < columnHeight) {
maxColumnHeight = columnHeight;
}
}
return CGSizeMake(0, maxColumnHeight + CXdefaultEdgeInsets.bottom);
}
@end