UICollectionView實(shí)現(xiàn)瀑布流框架

瀑布流.gif

基于完全自定義UICollectionViewLayout

#import "ViewController.h"
#import "GZDPhoto.h"
#import "GZDPhotoCell.h"
#import "GZDWaterFlowLayout.h"
//cellID
static NSString *const GZDCellID = @"photo";

@interface ViewController ()<UICollectionViewDataSource,GZDWaterFlowLayoutDelegate>
//將collectionView作為屬性
@property (weak,nonatomic) UICollectionView *collectionView;

/** 數(shù)據(jù)商品數(shù)組 */
@property (strong,nonatomic) NSMutableArray * photos;
@end

@implementation ViewController

#pragma mark - 懶加載
//圖片數(shù)組為從plist中加載
- (NSMutableArray *)photos {
    if (!_photos) {
        _photos =[GZDPhoto mj_objectArrayWithFile:[[NSBundle mainBundle] pathForResource:@"1.plist" ofType:nil]];
    }
    return _photos;
}

#pragma mark - 私有方法
- (void)viewDidLoad {
    [super viewDidLoad];
    //設(shè)置collectionView和做一些基本的配置
    [self setupCollectionView];
//設(shè)置刷新控件,模擬下拉刷新和上拉加載更多
    [self setupRefresh];   
}

//設(shè)置collectionView
- (void)setupCollectionView {
    //創(chuàng)建布局
#布局屬性完全繼承于UICollectionViewLayout基類
    GZDWaterFlowLayout *layout = [[GZDWaterFlowLayout alloc] init];
  //設(shè)置布局代理
    layout.delegate = self;
    //創(chuàng)建collectionView大小與控制器view的大小一致
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    //設(shè)置背景顏色
    collectionView.backgroundColor = [UIColor whiteColor];
    //注冊(cè)自定義cell,cell為從xib中描述
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GZDPhotoCell class]) bundle:nil] forCellWithReuseIdentifier:GZDCellID];
    //設(shè)置數(shù)據(jù)源
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
}
#pragma mark - <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.photos.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    GZDPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:GZDCellID forIndexPath:indexPath];
    cell.photo = self.photos[indexPath.item];
    return cell;
}

#pragma mark - <GZDWaterFlowLayoutDelegate>
## waterFlow代理方法 這個(gè)方法為@required 必須實(shí)現(xiàn),模型來(lái)源于控制器,所以控制器清楚每1個(gè)item的大小.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    GZDPhoto *photo = self.photos[indexPath.item];
//根據(jù)比例計(jì)算item的高度
    return [photo.h floatValue] * itemWidth / [photo.w floatValue];
}
#@optional 方法返回布局一共有多少列
- (NSUInteger)numberOfColsInWaterFlowLayout:(GZDWaterFlowLayout *)layout {
    
    return 3;
}
//控制四周cell與collectionView左右邊緣的距離
- (CGFloat)paddingInWaterFlowLayout:(GZDWaterFlowLayout *)layout {
    return 20;
}
//控制cell之間的距離
- (CGFloat)marginInWaterFlowLayout:(GZDWaterFlowLayout *)layout {
    return 30;
}
//控制cell四周的距離(主要是上下)
- (UIEdgeInsets)edgeInsetsInWaterFlowLayout:(GZDWaterFlowLayout *)layout {
    return (UIEdgeInsets){5,10,20,40};
}
@end
Snip20160325_1.png

瀑布流.png

WaterFlowLayout.h文件

#import <UIKit/UIKit.h>

@class GZDWaterFlowLayout;

##模仿tableview 使用代理來(lái)設(shè)計(jì)接口,達(dá)到解耦和,從外界控制布局內(nèi)部的改變的目的
@protocol GZDWaterFlowLayoutDelegate <NSObject>

@required
#必須實(shí)現(xiàn)的方法,返回item的行高.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath;
@optional
//控制列數(shù)
- (NSUInteger)numberOfColsInWaterFlowLayout:(GZDWaterFlowLayout *)layout;
//控制padding
- (CGFloat)paddingInWaterFlowLayout:(GZDWaterFlowLayout *)layout;
//控制margin
- (CGFloat)marginInWaterFlowLayout:(GZDWaterFlowLayout *)layout;
//控制item四周間距
- (UIEdgeInsets)edgeInsetsInWaterFlowLayout:(GZDWaterFlowLayout *)layout;

@end

@interface GZDWaterFlowLayout : UICollectionViewLayout

@property (weak,nonatomic) id<GZDWaterFlowLayoutDelegate> 
delegate;

@end

WaterFlowLayout.m文件


#import "GZDWaterFlowLayout.h"
/** 默認(rèn)的列數(shù) */
static CGFloat const GZDWaterFlowCols = 3;
/** 默認(rèn)的邊距 */
static CGFloat const GZDWaterFlowPadding = 10;
/** 默認(rèn)的邊距 */
static CGFloat const GZDWaterFolwMargin = 10;
/** 默認(rèn)的四邊距 */
static UIEdgeInsets const GZDWaterFlowEdgeInsets = {10,10,10,10};

@interface GZDWaterFlowLayout ()
/** 屬性數(shù)組 */
@property (strong,nonatomic) NSMutableArray * attributeses;
/** 行高數(shù)組 */
@property (strong,nonatomic) NSMutableArray * colHeights;
//getter方法聲明
- (NSUInteger)cols;
- (CGFloat)margin;
- (CGFloat)padding;
- (UIEdgeInsets)edgeInsets;

@end

@implementation GZDWaterFlowLayout

#pragma mark - getter方法實(shí)現(xiàn)
- (NSUInteger)cols {
    if ([self.delegate respondsToSelector:@selector(numberOfColsInWaterFlowLayout:)]) {
        return [self.delegate numberOfColsInWaterFlowLayout:self];
    }else {
        return GZDWaterFlowCols;
    }
}

- (CGFloat)margin {
    if ([self.delegate respondsToSelector:@selector(marginInWaterFlowLayout:)]) {
        return [self.delegate marginInWaterFlowLayout:self];
    }else {
        return GZDWaterFolwMargin;
    }
}

- (CGFloat)padding {
    if ([self.delegate respondsToSelector:@selector(paddingInWaterFlowLayout:)]) {
        return [self.delegate paddingInWaterFlowLayout:self];
    }else {
        return GZDWaterFlowPadding;
    }
}

- (UIEdgeInsets)edgeInsets {
    if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterFlowLayout:)]) {
        return [self.delegate edgeInsetsInWaterFlowLayout:self];
    }else {
        return GZDWaterFlowEdgeInsets;
    }
}



#pragma mark - 懶加載
- (NSMutableArray *)attributes {//屬性數(shù)組
    if (!_attributeses) {
        _attributeses = [NSMutableArray array];
    }
    return _attributeses;
}

- (NSMutableArray *)colHeights {//行高數(shù)組
    if (!_colHeights) {
        _colHeights = [NSMutableArray array];
    }
    return _colHeights;
}
/** 做一些準(zhǔn)備,在初始化的時(shí)候只會(huì)調(diào)一次,重新刷新時(shí)候會(huì)調(diào)用該方法 */
- (void)prepareLayout {
    //一定要調(diào)super
    [super prepareLayout];
//移除所有的行高元素,需要重新算一遍
    [self.colHeights removeAllObjects];
//添加默認(rèn)的元素,即默認(rèn)行高是頂部的間距
    for (NSInteger i = 0; i < self.cols; i++) {
        [self.colHeights addObject:@(self.edgeInsets.top)];
    }
    //移除所有的布局元素
    [self.attributeses removeAllObjects];
    //只需要計(jì)算一次
    for (NSInteger i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        //創(chuàng)建indexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        //創(chuàng)建indexPath處的布局元素
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        //添加進(jìn)布局元素?cái)?shù)組
        [self.attributeses addObject:attributes];
    }
    
    
}

//返回布局元素?cái)?shù)組,有多少個(gè)item就有多少個(gè)布局元素 --如果繼承自最初始的布局時(shí) 調(diào)用非常的頻繁,所以在prepareLayout方法中計(jì)算布局屬性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attributeses;
}

##返回indexPath位置的布局元素  -- 核心代碼

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //最短的那一行的行數(shù)
    NSInteger minColNum = 0;
    //最短的那一行的行高
    CGFloat minColHeight = MAXFLOAT;
    //遍歷行高數(shù)組
    for (NSInteger i = 0; i < self.cols; i++) {
        CGFloat colHeight = [self.colHeights[i] floatValue];
        if (minColHeight > colHeight) {
            minColHeight = colHeight;
            minColNum = i;
        }
    }
    CGFloat cellW = (self.collectionView.bounds.size.width - 2 * self.padding - (self.cols - 1) * self.margin) / self.cols;
    //由于是必須實(shí)現(xiàn)的方法所以不需要判斷
    CGFloat cellH = [self.delegate waterFlowLayout:self itemWidth:cellW heightForItemAtIndexPath:indexPath];
    CGFloat cellY = minColHeight + self.edgeInsets.top;
    CGFloat cellX = self.padding + minColNum * (self.margin + cellW);
    attributes.frame = CGRectMake(cellX, cellY, cellW, cellH);
    //更新行高數(shù)組
    self.colHeights[minColNum] = @(CGRectGetMaxY(attributes.frame));
    return attributes;
}
//返回contentSize
- (CGSize)collectionViewContentSize {
    //遍歷取出最大的那一個(gè)行高
    CGFloat maxHeight = [self.colHeights[0] floatValue];
    for (NSInteger i = 1; i < self.colHeights.count; i++) {
        CGFloat height = [self.colHeights[i] floatValue];
        if (height > maxHeight) {
            maxHeight = height;
        }
    }
    return (CGSize){0,maxHeight + self.padding};
}
@end

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,882評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,208評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,746評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,666評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,477評(píng)論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,960評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,047評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,200評(píng)論 0 288
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,726評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,617評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,807評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,327評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,049評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,425評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,674評(píng)論 1 281
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,432評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,769評(píng)論 2 372

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,151評(píng)論 4 61
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,610評(píng)論 25 708
  • 暮色的云,等不來(lái)想要等的人。小深:十八歲,雙魚女,偶爾寫字讀詩(shī),立黃昏的小徒弟。立黃昏:二十二歲,雙魚男,偶爾吃飯...
    立黃昏閱讀 1,062評(píng)論 57 37
  • 夜永遠(yuǎn)等待綻放黎明 在喧囂之后 落入沉靜 光漸漸充盈著 無(wú)所謂星辰與海洋 無(wú)懼于困難與悲傷 像站在懸崖上的極限挑戰(zhàn)...
    寫作的沐陽(yáng)愛畫畫閱讀 188評(píng)論 0 1
  • 四圣諦:苦集滅道 五蘊(yùn) 色蘊(yùn):包括自身的眼、耳、鼻、舌、身等五根,以及反映自身而起感受作用的色、聲、香、味、觸的五...
    monchhichi1005閱讀 375評(píng)論 0 0