做過電商類 App 的朋友對瀑布流一定不陌生,商品列表、圖片牆幾乎都離不開它。本文把瀑布流的實現思路梳理清楚,並一步步封裝出一個可複用的布局類。
下面就用第二種思路,動手封裝一個小框架。
默認兩列的效果:

其他案例
上面那個動畫裡的布局切換,同樣是自定義 UICollectionViewLayout 完成的。可見只要重寫好幾個關鍵方法,就能靈活控制靜態圖片的排布方式。
1. prepareLayout:每次 collectionView 刷新布局時只會調用一次,適合放初始化工作。
2. layoutAttributesForElementsInRect::返回當前矩形區域內所有 cell 對應的 attribute 對象,系統據此完成布局。
3. layoutAttributesForItemAtIndexPath::每個 cell 即將出現時都會被調用一次,核心的位置計算邏輯就寫在這裡。
4. collectionViewContentSize:算出整個內容區域的尺寸,滾動才有依據。
// 每一列的間距 static const CGFloat MKJDefaultColumnMargin = 10; // 每一行間距 static const CGFloat MKJDefaultRowMargin = 10; // 整體的上間距,左間距,下間距,右間距 static const UIEdgeInsets MKJDefaultEdgeInsets = {10,10,10,10}; // 默認是多少列 static const NSUInteger MKJDefaultColumnCounts = 2; @interface MKJWaterFallLayout () @property (nonatomic,strong) NSMutableArray *attributeArr; // cell屬性的數組 @property (nonatomic,strong) NSMutableArray *columnHeightArr; // 每列的高度數組 @end
// 每次刷新會調用一次 - (void)prepareLayout { [super prepareLayout]; // 每次重新刷新的時候清除之前的所有高度值,默認就是UIEdg給定的top [self.columnHeightArr removeAllObjects]; for (NSInteger i = 0; i < [self columnCount]; i++) { [self.columnHeightArr addObject:@([self insetMargin].top)]; } // 每次刷新把對應的att屬性清空 [self.attributeArr removeAllObjects]; // 初始化一次每個cell對應的attribute屬性 NSInteger count = [self.collectionView numberOfItemsInSection:0]; for (NSInteger i = 0; i < count; i++) { NSIndexPath *indexpath = [NSIndexPath indexPathForItem:i inSection:0]; UICollectionViewLayoutAttributes *attribute = [self layoutAttributesForItemAtIndexPath:indexpath]; [self.attributeArr addObject:attribute]; } }
// 返回attribute屬性數組決定最後的排布 - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { return self.attributeArr; } // 返回對應的indexpath下每個cell的屬性 cell的出現會一直刷新該方法 - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath { // 初始化布局屬性---> 對應的indexpath UICollectionViewLayoutAttributes *att = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; CGFloat collectionW = self.collectionView.frame.size.width; // 寬度是根據列數和間距固定算出來的 CGFloat width = (collectionW - [self insetMargin].left - [self insetMargin].right - ([self columnCount] - 1) * [self columnMargin]) / [self columnCount]; // 高度是根據代理的數據源返回比例計算的 CGFloat height = [self.delegate MKJWaterFallLayout:self heightForItemAtIndexPath:indexPath] * width; // X 和 Y值都是在找出最小column之後才能確定,核心就是根據列數,找出最小高度的那一列 // 先取出第一個默認是最小的 CGFloat minColumnHeight = [self.columnHeightArr[0] doubleValue]; // 默認最小的是第0列 NSUInteger finalCol = 0; for (NSInteger i = 1 ; i < [self columnCount]; i++) { CGFloat currentColHeight = [self.columnHeightArr[i] doubleValue]; if (minColumnHeight > currentColHeight) { minColumnHeight = currentColHeight; finalCol = i; } } // x,y值是根據最小高度列算出來的 CGFloat x = [self insetMargin].left + (width + [self columnMargin]) * finalCol; CGFloat y = minColumnHeight; // 當你是一個行排布的時候 默認是top值,不需要加間距 NSInteger count = indexPath.item; if ((count / ([self columnCount])) >= 1) { y += [self rowMargin]; } att.frame = CGRectMake(x, y, width, height); self.columnHeightArr[finalCol] = @(CGRectGetMaxY(att.frame)); return att; }
整套計算本質上就是給每個 cell 逐一算出 frame,拆開來看:
1. 寬度由列數、左右內邊距和列間距共同決定,這些值既可以寫死,也可以交給代理動態返回。
2. 高度無法預知,必須由外部代理按內容比例提供。
3. X 座標的關鍵在於「找最矮的那一列」。用一個數組緩存每列的當前高度,遍歷取出最小值及其列序號,再結合列寬與列間距換算出 X。
4. Y 座標直接取該列當前高度;如果不是第一行,還要補上行間距。定位完成後別忘了把新高度寫回數組,供下一個 cell 判斷。
// 計算出滾動區域的大小 - (CGSize)collectionViewContentSize { CGFloat maxColumHeight = [self.columnHeightArr[0] doubleValue]; for (NSInteger i = 1; i < [self columnCount]; i++) { CGFloat currentColHeight = [self.columnHeightArr[i] doubleValue]; if (maxColumHeight < currentColHeight) { maxColumHeight = currentColHeight; } } return CGSizeMake(0, maxColumHeight + [self insetMargin].bottom); }
// 聲明如下 - (UICollectionView *)colletionView { if (_colletionView == nil) { MKJWaterFallLayout *layout = [[MKJWaterFallLayout alloc] init]; layout.delegate = self; UICollectionView *collectionV = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout]; collectionV.backgroundColor = [UIColor redColor]; [collectionV registerNib:[UINib nibWithNibName:productID bundle:nil] forCellWithReuseIdentifier:productID]; collectionV.delegate = self; collectionV.dataSource = self; _colletionView = collectionV; } return _colletionView; } // 內部行數,間距的控制 #pragma mark - waterfallLayoutDelegate - (CGFloat)MKJWaterFallLayout:(MKJWaterFallLayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath { // 返回寬度和高度比例 MKJProductModel *product = self.dataSource[indexPath.item]; return product.h / product.w; } // 控制列間距 - (CGFloat)columnMarginForWaterFallLayout:(MKJWaterFallLayout *)collectionViewLayout { return 10; } // 控制行間距 - (CGFloat)rowMarginForWaterFallLayout:(MKJWaterFallLayout *)collectionViewLayout { return 30; } // 控制列數 - (NSUInteger)columnCountForWaterFallLayout:(MKJWaterFallLayout *)collectionViewLayout { // if (self.dataSource.count > 50) { // return 3; // } return 3; } // 控制整體上左下右間距 - (UIEdgeInsets)insetForWaterFallLayout:(MKJWaterFallLayout *)collectionViewLayout { return UIEdgeInsetsMake(10, 10, 10, 10); }
Demo 地址:https://xiazai.jb51.net/201702/yuanma/MKJWaterFallLayout_jb51.rar
以上就是瀑布流布局的完整實現過程,核心只有一句話:始終把新 cell 放進當前最矮的那一列。