UICollectionView 瀑布流的使用

b10l07發表於2016-05-25

緣由:最近專案中瀑布流遇到的機率相當高,想想以前就是直接用CHTCollectionViewWaterfallLayout,並沒有詳細去看裡面的實現,回來後自己就跟著寫一遍,特此記錄。

一、瞭解原生UICollectionViewLayout的幾個方法
#pragma mark - 準備佈局
- (void)prepareLayout;
#pragma mark - 當尺寸有所變化時,重新重新整理
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds; 
#pragma mark - 處理所有的Item的layoutAttributes
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
#pragma mark - 處理單個的Item的layoutAttributes
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
#pragma mark - CollectionView的滾動範圍
- (CGSize)collectionViewContentSize;

以上幾個方法,都是需要重寫父類的方法,實現瀑布流佈局。

二、實現上述幾個方法的實際情況

此處下面程式碼轉載UICollectionView詳解:瀑布流, 寫的很清楚,然後我們在使用 UICollectionView 的時候只要將
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout 中的 layout 換成自己的自定義的就 OK,同時不忘記使用其代理的實現就讓瀑布流出來啦。

#import <UIKit/UIKit.h>

@protocol PQWaterFlowLayoutDelegate;

@interface PQWaterFlowLayout : UICollectionViewLayout

// cell的列間距
@property (nonatomic, assign) CGFloat columnMargin;
// cell的行間距
@property (nonatomic, assign) CGFloat rowMargin;
// cell的top,right,bottom,left間距
@property (nonatomic, assign) UIEdgeInsets insets;
// 顯示多少列
@property (nonatomic, assign) NSInteger count;
// delegate
@property (nonatomic, weak) id <PQWaterFlowLayoutDelegate> delegate;

@end

@protocol PQWaterFlowLayoutDelegate <NSObject>

/*通過代理獲得每個cell的高度(之所以用代理取得高度的值,就是為了解耦,這裡定義的LFWaterFlowLayout不依賴與任務模型資料)*/
- (CGFloat)waterFlowLayout:(PQWaterFlowLayout *)waterFlowLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath;

@end
#import "PQWaterFlowLayout.h"

@interface PQWaterFlowLayout ()

/* Key: 第幾列; Value: 儲存每列的cell的底部y值 */
@property (nonatomic,strong) NSMutableDictionary *cellInfo;

@end

@implementation PQWaterFlowLayout

#pragma mark - 初始化屬性
- (instancetype)init {
    self = [super init];
    if (self) {
        self.columnMargin = 10;
        self.rowMargin = 10;
        self.insets = UIEdgeInsetsMake(10, 10, 10, 10);
        self.count = 2;
    }
    return self;
}

- (NSMutableDictionary *)cellInfo {
    if (!_cellInfo) {
        _cellInfo = [NSMutableDictionary dictionary];
    }
    return _cellInfo;
}


#pragma mark - 當尺寸有所變化時,重新重新整理
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}
#pragma mark - 準備佈局
- (void)prepareLayout {
    [super prepareLayout];
    
    for (int i=0; i<self.count; i++) {
        NSString *index = [NSString stringWithFormat:@"%d",i];
        self.cellInfo[index] = @(self.insets.top);
    }
}

#pragma mark - 處理所有的Item的layoutAttributes
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    // 每次重新佈局之前,先清除掉以前的資料(因為螢幕滾動的時候也會呼叫)
    __weak typeof (self) wSelf = self;
    [self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *minY, BOOL *stop) {
        wSelf.cellInfo[columnIndex] = @(wSelf.insets.top);
    }];
    
    
    NSMutableArray *array = [NSMutableArray array];
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    for (int i=0; i<count; i++) {
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        [array addObject:attrs];
    }
    
    return array;
}

#pragma mark - 處理單個的Item的layoutAttributes
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 獲取cell底部Y值最小的列
    __block NSString *minYForColumn = @"0";
    __weak typeof (self) wSelf = self;
    [self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *minY, BOOL *stop) {
        if ([minY floatValue] < [wSelf.cellInfo[minYForColumn] floatValue]) {
            minYForColumn = columnIndex;
        }
    }];
    
    CGFloat width = (self.collectionView.frame.size.width - self.insets.left - self.insets.right - self.columnMargin * (self.count - 1)) / self.count;
    CGFloat height = [self.delegate waterFlowLayout:self heightForWidth:width atIndexPath:indexPath];
    CGFloat x = self.insets.left + (width + self.columnMargin) * [minYForColumn integerValue];
    CGFloat y = self.rowMargin + [self.cellInfo[minYForColumn] floatValue];
    
    self.cellInfo[minYForColumn] = @(y + height);
    
    // 建立屬性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.frame = CGRectMake(x, y, width, height);
    return attrs;
}

#pragma mark - CollectionView的滾動範圍
- (CGSize)collectionViewContentSize {
    CGFloat width = self.collectionView.frame.size.width;
    
    __block CGFloat maxY = 0;
    [self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *itemMaxY, BOOL *stop) {
        if ([itemMaxY floatValue] > maxY) {
            maxY = [itemMaxY floatValue];
        }
    }];
    
    return CGSizeMake(width, maxY + self.insets.bottom);
}


@end

三、具體思路的實現

3-1、確定滾動方向、預設列數、行間距、列間距

self.columnMargin = 10;
self.rowMargin = 10;
self.insets = UIEdgeInsetsMake(10, 10, 10, 10);
self.count = 2;

3-2、可以提供一個陣列(記錄當前每一列的最大Y值),假如count,我們就提供一個count個元素的陣列,記錄所有佈局屬性。

 for (int i=0; i<self.count; i++) {
        NSString *index = [NSString stringWithFormat:@"%d",i];
        self.cellInfo[index] = @(self.insets.top);
 }

3-3、在layoutAttributesForElementsInRect:方法(返回所有元素的佈局屬性陣列 ),並儲存。

__weak typeof (self) wSelf = self;
[self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *minY, BOOL *stop) {
    wSelf.cellInfo[columnIndex] = @(wSelf.insets.top);
}];
NSMutableArray *array = [NSMutableArray array];
NSInteger count = [self.collectionView numberOfItemsInSection:0];

for (int i=0; i<count; i++) {
    UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    [array addObject:attrs];
}

return array;

3-4、我們可以在layoutAttributesForItemAtIndexPath: 方法: 來調整 Cell的佈局屬性 , 指定Cell的 frame, 這個就是最核心的確定了frame

CGFloat width = (self.collectionView.frame.size.width - self.insets.left - self.insets.right - self.columnMargin * (self.count - 1)) / self.count;
CGFloat height = [self.delegate waterFlowLayout:self heightForWidth:width atIndexPath:indexPath];
CGFloat x = self.insets.left + (width + self.columnMargin) * [minYForColumn integerValue];
CGFloat y = self.rowMargin + [self.cellInfo[minYForColumn] floatValue];

self.cellInfo[minYForColumn] = @(y + height);

// 建立屬性
UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
attrs.frame = CGRectMake(x, y, width, height);

3-5、設定collectionView的contentSize,讓其正常滾動。

CGFloat width = self.collectionView.frame.size.width;
__block CGFloat maxY = 0;
[self.cellInfo enumerateKeysAndObjectsUsingBlock:^(NSString *columnIndex, NSNumber *itemMaxY, BOOL *stop) {
    if ([itemMaxY floatValue] > maxY) {
        maxY = [itemMaxY floatValue];
    }
}];

return CGSizeMake(width, maxY + self.insets.bottom);

當然,我們平常用的時候,只要用CHTCollectionViewWaterfallLayout這個就 OK 了,比較完善,而且專案一直在更新中,強烈推薦。

相關文章