幾個原因,講起來很樸實:
客戶類(通常就是 delegate 的持有者):把業務邏輯委託出去,自己只負責在對的時機發問。
真實角色:把客戶類需要的業務邏輯抽象成一份方法清單,也就是代理協議。
代理協議的角色是:
代理角色:
@required 方法。文字描述總是抽象,一張圖勝過一堆形容詞:

先釐清業務邏輯:

而「每一個 cell 該怎麼擺」這段邏輯最複雜,附上一張思維導圖:

核心原則:封裝提供的介面,要按客戶類的業務需求來定。具體拆成幾條:
@class LYPWaterFlowLayout;
@protocol LYPWaterFlowLayoutDelegate <NSObject>
// 必須實作
/** 取得瀑布流每個元素的高度 */
- (CGFloat)waterFlowLayout:(LYPWaterFlowLayout *)waterFlowLayout
heightForItemAtIndex:(NSInteger)index
itemWith:(CGFloat)itemWith;
// 選擇性實作
@optional
/** 列數 */
- (NSInteger)columnCountInWaterFlowLayout:(LYPWaterFlowLayout *)waterFlowLayout;
/** 列間距 */
- (CGFloat)columnMarginInWaterFlowLayout:(LYPWaterFlowLayout *)waterFlowLayout;
/** 行間距 */
- (CGFloat)rowMarginInWaterFlowLayout:(LYPWaterFlowLayout *)waterFlowLayout;
/** 內邊距 */
- (UIEdgeInsets)edgeInsetsInWaterFlowLayout:(LYPWaterFlowLayout *)waterFlowLayout;
@end
@interface LYPWaterFlowLayout : UICollectionViewLayout /** 代理 */ @property (nonatomic, weak) id<LYPWaterFlowLayoutDelegate> delegate; @end
這裡用 weak 而非 strong,是為了避免循環引用——控制器持有布局物件,布局物件又不該反過來把控制器留著。
/** 預設列數 */
static const NSInteger LYPDefaultColumnCount = 3;
/** 預設列間距 */
static const CGFloat LYPDefaultColumnMargin = 10;
/** 預設行間距 */
static const CGFloat LYPDefaultRowMargin = 10;
/** 預設內邊距 */
static const UIEdgeInsets LYPDefaultEdgeInsets = {10, 10, 10, 10};
- (NSInteger)columnCount {
// 判斷代理是否實作了取得列數的選擇性方法
if ([self.delegate respondsToSelector:@selector(columnCountInWaterFlowLayout:)]) {
// 有實作:採用代理設定的值
return [self.delegate columnCountInWaterFlowLayout:self];
} else {
// 未實作:退回預設值
return LYPDefaultColumnCount;
}
}
其餘三個屬性(列間距、行間距、內邊距)的 getter 幾乎一模一樣,只是換掉 selector 與預設常數,此處不再重複貼。這正是用 respondsToSelector: 把「可選」這件事落地的標準寫法。
/** 所有 cell 的布局屬性 */ @property (nonatomic, strong) NSMutableArray *attrsArray; /** 每一列目前的累積高度 */ @property (nonatomic, strong) NSMutableArray *columnHeights;
- (NSMutableArray *)attrsArray {
if (_attrsArray == nil) {
_attrsArray = [NSMutableArray array];
}
return _attrsArray;
}
- (NSMutableArray *)columnHeights {
if (_columnHeights == nil) {
_columnHeights = [NSMutableArray array];
}
return _columnHeights;
}
prepareLayout 是 UICollectionViewLayout 的關鍵回呼——它會在每次布局前被呼叫一次,適合把所有 frame 一次算完並快取起來,避免滾動時反覆計算。
- (void)prepareLayout {
[super prepareLayout];
// 清除上次計算的所有列高
[self.columnHeights removeAllObjects];
// 設定所有列的初始高度為內邊距頂部
for (NSInteger i = 0; i < self.columnCount; i++) {
self.columnHeights[i] = @(self.edgeInsets.top);
}
// 清除上次的所有布局屬性
[self.attrsArray removeAllObjects];
// 逐一建立每個 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];
}
}
- (nullable NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.attrsArray;
}
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
// 先確定尺寸
CGFloat collectionViewWidth = self.collectionView.frame.size.width;
CGFloat width = (collectionViewWidth
- self.edgeInsets.left
- self.edgeInsets.right
- (self.columnCount - 1) * self.columnMargin) / self.columnCount;
// 高度由代理決定
CGFloat height = [self.delegate waterFlowLayout:self heightForItemAtIndex:indexPath.item itemWith:width];
// 找出目前最矮的那一列
NSInteger destColumn = 0;
CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
for (NSInteger i = 1; i < self.columnCount; i++) {
CGFloat columnHeight = [self.columnHeights[i] doubleValue];
if (minColumnHeight > columnHeight) {
minColumnHeight = columnHeight;
destColumn = i;
}
}
// 計算座標
CGFloat x = self.edgeInsets.left + destColumn * (width + self.columnMargin);
CGFloat y = minColumnHeight;
if (y != self.edgeInsets.top) { // 不是第一行才需要加行間距
y += self.rowMargin;
}
attrs.frame = CGRectMake(x, y, width, height);
// 更新該列的累積高度
self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
return attrs;
}
這段就是瀑布流的靈魂:每次把新元素放進當前最矮的那一列,放下後更新該列高度,下一個元素自然就會去找新的最矮列。這個「貪婪」策略保證了各列高度差始終最小,視覺上最整齊。
- (CGSize)collectionViewContentSize {
CGFloat maxColumnHeight = [self.columnHeights[0] doubleValue];
for (NSInteger i = 1; i < self.columnCount; i++) {
CGFloat columnHeight = [self.columnHeights[i] doubleValue];
if (maxColumnHeight < columnHeight) {
maxColumnHeight = columnHeight;
}
}
// 高度取最高那一列,再留一個行間距作為底部餘裕
return CGSizeMake(0, maxColumnHeight + self.rowMargin);
}
整套封裝下來,對外的介面只有一個 delegate 屬性和一個協議。使用者要做的僅僅是實作「回傳高度」這個必選方法,其餘全部有合理預設值;想微調時再按需實作可選方法即可。把變化點交給使用者、把不變的計算邏輯留給自己,這是自定義布局封裝最值得記住的思路。