UICollectionView 瀑布流的使用

緣由:最近項目中瀑布流遇到的機率相當高罪郊,想想以前就是直接用CHTCollectionViewWaterfallLayout益愈,并沒有詳細去看里面的實現(xiàn),回來后自己就跟著寫一遍饼灿,特此記錄幕侠。

一、了解原生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;

以上幾個方法晤硕,都是需要重寫父類的方法,實現(xiàn)瀑布流布局庇忌。

二舞箍、實現(xiàn)上述幾個方法的實際情況

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

#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不依賴與任務(wù)模型數(shù)據(jù))*/
- (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 {
    
    // 每次重新布局之前,先清除掉以前的數(shù)據(jù)(因為屏幕滾動的時候也會調(diào)用)
    __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);
    
    // 創(chuàng)建屬性
    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

三残制、具體思路的實現(xiàn)

3-1立砸、確定滾動方向、默認列數(shù)初茶、行間距颗祝、列間距

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

3-2、可以提供一個數(shù)組(記錄當前每一列的最大Y值),假如count螺戳,我們就提供一個count個元素的數(shù)組搁宾,記錄所有布局屬性。

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

3-3倔幼、在layoutAttributesForElementsInRect:方法(返回所有元素的布局屬性數(shù)組 )盖腿,并保存。

__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: 方法: 來調(diào)整 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);

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

3-5茂卦、設(shè)置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 了伶贰,比較完善而咆,而且項目一直在更新中,強烈推薦幕袱。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市悠瞬,隨后出現(xiàn)的幾起案子们豌,更是在濱河造成了極大的恐慌,老刑警劉巖浅妆,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件望迎,死亡現(xiàn)場離奇詭異,居然都是意外死亡凌外,警方通過查閱死者的電腦和手機辩尊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來康辑,“玉大人摄欲,你說我怎么就攤上這事〈保” “怎么了胸墙?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長按咒。 經(jīng)常有香客問我迟隅,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任智袭,我火速辦了婚禮奔缠,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘吼野。我一直安慰自己校哎,他們只是感情好,可當我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布箫锤。 她就那樣靜靜地躺著贬蛙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪谚攒。 梳的紋絲不亂的頭發(fā)上阳准,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天,我揣著相機與錄音馏臭,去河邊找鬼野蝇。 笑死,一個胖子當著我的面吹牛括儒,可吹牛的內(nèi)容都是我干的绕沈。 我是一名探鬼主播,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼帮寻,長吁一口氣:“原來是場噩夢啊……” “哼乍狐!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起固逗,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤浅蚪,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后烫罩,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體惜傲,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年贝攒,在試婚紗的時候發(fā)現(xiàn)自己被綠了盗誊。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡隘弊,死狀恐怖哈踱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情长捧,我是刑警寧澤嚣鄙,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站串结,受9級特大地震影響哑子,放射性物質(zhì)發(fā)生泄漏舅列。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一卧蜓、第九天 我趴在偏房一處隱蔽的房頂上張望帐要。 院中可真熱鬧,春花似錦弥奸、人聲如沸榨惠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽赠橙。三九已至,卻和暖如春愤炸,著一層夾襖步出監(jiān)牢的瞬間期揪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工规个, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留凤薛,地道東北人。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓诞仓,卻偏偏與公主長得像缤苫,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子墅拭,可洞房花燭夜當晚...
    茶點故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內(nèi)容