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];
    //注冊自定義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代理方法 這個方法為@required 必須實(shí)現(xiàn),模型來源于控制器,所以控制器清楚每1個item的大小.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    GZDPhoto *photo = self.photos[indexPath.item];
//根據(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 使用代理來設(shè)計接口,達(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)備,在初始化的時候只會調(diào)一次,重新刷新時候會調(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];
    //只需要計算一次
    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)布局元素數(shù)組
        [self.attributeses addObject:attributes];
    }
    
    
}

//返回布局元素數(shù)組,有多少個item就有多少個布局元素 --如果繼承自最初始的布局時 調(diào)用非常的頻繁,所以在prepareLayout方法中計算布局屬性
- (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 {
    //遍歷取出最大的那一個行高
    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)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市忙厌,隨后出現(xiàn)的幾起案子哲身,更是在濱河造成了極大的恐慌撤师,老刑警劉巖指攒,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件劣欢,死亡現(xiàn)場離奇詭異忽洛,居然都是意外死亡锭碳,警方通過查閱死者的電腦和手機(jī)涣楷,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進(jìn)店門分唾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人狮斗,你說我怎么就攤上這事绽乔。” “怎么了碳褒?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵折砸,是天一觀的道長。 經(jīng)常有香客問我沙峻,道長睦授,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任摔寨,我火速辦了婚禮去枷,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘是复。我一直安慰自己删顶,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布淑廊。 她就那樣靜靜地躺著逗余,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蒋纬。 梳的紋絲不亂的頭發(fā)上猎荠,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天,我揣著相機(jī)與錄音蜀备,去河邊找鬼关摇。 笑死,一個胖子當(dāng)著我的面吹牛碾阁,可吹牛的內(nèi)容都是我干的输虱。 我是一名探鬼主播,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼脂凶,長吁一口氣:“原來是場噩夢啊……” “哼宪睹!你這毒婦竟也來了愁茁?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤亭病,失蹤者是張志新(化名)和其女友劉穎鹅很,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體罪帖,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡促煮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了整袁。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片菠齿。...
    茶點(diǎn)故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖坐昙,靈堂內(nèi)的尸體忽然破棺而出绳匀,到底是詐尸還是另有隱情,我是刑警寧澤炸客,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布疾棵,位于F島的核電站,受9級特大地震影響嚷量,放射性物質(zhì)發(fā)生泄漏乖仇。R本人自食惡果不足惜说莫,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望赊时。 院中可真熱鬧宣渗,春花似錦抖所、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至鞍恢,卻和暖如春傻粘,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背帮掉。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工弦悉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蟆炊。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓稽莉,卻偏偏與公主長得像,于是被迫代替她去往敵國和親涩搓。 傳聞我的和親對象是個殘疾皇子污秆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評論 2 355

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫劈猪、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,104評論 4 62
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,139評論 25 707
  • 暮色的云,等不來想要等的人庸推。小深:十八歲贡避,雙魚女,偶爾寫字讀詩予弧,立黃昏的小徒弟刮吧。立黃昏:二十二歲,雙魚男掖蛤,偶爾吃飯...
    立黃昏閱讀 1,049評論 57 37
  • 夜永遠(yuǎn)等待綻放黎明 在喧囂之后 落入沉靜 光漸漸充盈著 無所謂星辰與海洋 無懼于困難與悲傷 像站在懸崖上的極限挑戰(zhàn)...
    寫作的沐陽愛畫畫閱讀 184評論 0 1
  • 四圣諦:苦集滅道 五蘊(yùn) 色蘊(yùn):包括自身的眼杀捻、耳、鼻蚓庭、舌致讥、身等五根,以及反映自身而起感受作用的色器赞、聲垢袱、香、味港柜、觸的五...
    monchhichi1005閱讀 361評論 0 0