iOS-CollectionView瀑布流框架搭建

CollectionView實(shí)現(xiàn)以下效果.

Simulator Screen Shot 2016年5月24日 上午9.32.54.png

思路:
先說一下這個效果的實(shí)現(xiàn)思路,首先需要確定該瀑布流有多少列,然后需要確定每個cell 的高度,用一個數(shù)組記錄下每一列的已添加上去的cell的高度和.然后添加下一個cell的時候找出所有列中高度最小的列,再添加上去.
例如:在該例子中,總共有兩列,當(dāng)添加完第一第二個cell,即第一行添加完了,要添加第三個cell,就需要找出第一第二列中高度最短的那一列,然后添加到最短那一列下面,以此類推.

3.png

實(shí)現(xiàn):
首先我們需要初始化collectionView,步驟與 "iOS-CollectionView 基礎(chǔ)" 類似.

該效果需要自定義布局,實(shí)現(xiàn)瀑布流效果.
創(chuàng)建一個布局類,繼承于UICollectionViewLayout. (流水布局對應(yīng)的類繼承于UICollectionViewFlowLayout, UICollectionViewFlowLayout 是 UICollectionViewLayout的子類)

在布局類需要重寫四個方法,分別是:

1. 重寫prepareLayout方法

-作用:在這個方法做一些初始化操作
-注意:一定要調(diào)用 [super prepareLayout]

2.重寫layoutAttributesForItemAtIndexPath:方法

-作用:返回indexPath 位置cell對應(yīng)的布局屬性

3. 重寫layoutAttributesForElementsInRect:方法

-作用:
這個方法的返回值是個數(shù)組
這個數(shù)組中存放的是UICollectionViewLayoutAttributes對象
UICollectionViewLayoutAttributes 對象決定了cell的排布方式

4.重寫collectionViewContentSize方法

-作用:決定collectionView的可滾動范圍

代碼實(shí)現(xiàn):
布局類.m 文件

1.定義如下靜態(tài)變量

/**  列數(shù)*/
static const CGFloat columCount = 3;
/**  每一列間距*/
static const CGFloat columMargin = 10;
/**  每一列間距*/
static const CGFloat rowMargin = 10;
/**  邊緣間距*/
static const UIEdgeInsets defaultEdgeInsets = {10,10,10,10};

2.聲明兩個屬性

/** 布局屬性數(shù)組*/
@property (nonatomic,strong) NSMutableArray *attrsArray;

/** 存放所有列的當(dāng)前高度*/
@property (nonatomic,strong) NSMutableArray *columnHeight;

懶加載 attrsArray, columnHeight

- (NSMutableArray *)attrsArray
{
    if (!_attrsArray) {
        
        _attrsArray = [NSMutableArray array];
    }
    return _attrsArray;
}

- (NSMutableArray *)columnHeight
{
    if (!_columnHeight) {
        
        _columnHeight = [NSMutableArray array];
    }
    return _columnHeight;
}

重寫prepareLayout方法

/**  初始化*/
- (void)prepareLayout
{
    [super prepareLayout];
   
    //如果刷新布局就會重新調(diào)用prepareLayout這個方法,所以要先把高度數(shù)組清空
    [self.columnHeight removeAllObjects];
    for (int i = 0; i < self.columCount; i++) {
        
        [self.columnHeight addObject:@(self.defaultEdgeInsets.top)];
    }
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    [self.attrsArray removeAllObjects];
    for (NSInteger i = 0; i < count; i++) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
        //獲取indexPath 對應(yīng)cell 的布局屬性
        UICollectionViewLayoutAttributes *attr = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attrsArray addObject:attr];
    }
}

該方法返回對應(yīng)cell上的布局屬性.我們可以在這個方法中設(shè)置cell 的布局樣式.在prepareLayout方法中,我們根據(jù)這個方法,傳入對應(yīng)的IndexPath從而獲取到布局屬性attr,然后添加到數(shù)組中.

/**
*  返回indexPath 位置cell對應(yīng)的布局屬性
*/
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
   UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

   //使用for循環(huán),找出高度最短的那一列
   //最短高度的列
   NSInteger destColumn = 0;
   CGFloat minColumnHeight = [self.columnHeight[0] doubleValue];
   
   for (NSInteger i = 1; i < self.columCount; i++) {
       
       CGFloat columnHeight  =[self.columnHeight[i] doubleValue];
       if (minColumnHeight > columnHeight) {
           
           minColumnHeight = columnHeight;
           destColumn = i;
       }
   }
   
   CGFloat w = (self.collectionView.frame.size.width - self.defaultEdgeInsets.left - self.defaultEdgeInsets.right - (self.columCount - 1) * self.columMargin )/self.columCount;

   //(使用代理在外部決定cell 的高度,下面會介紹)
   CGFloat h = [self.delegate waterFlowLayout:self heightForRowAtIndex:indexPath.item itemWidth:w];
   
   CGFloat x = self.defaultEdgeInsets.left + destColumn*(w + self.columMargin);
   CGFloat y = minColumnHeight ;
   
   if (y != self.defaultEdgeInsets.top) {
       
       y += self.rowMargin;
   }

   attr.frame = CGRectMake(x,y,w,h);
   
   self.columnHeight[destColumn] =  @(y+ h);
   return attr;
}

重寫layoutAttributesForElementsInRect:方法

/**
 *  決定cell 的排布
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.attrsArray;
}

決定collectionView的可滾動范圍

- (CGSize)collectionViewContentSize
{
    
    CGFloat maxHeight = [self.columnHeight[0] doubleValue];
    for (int i = 1; i < self.columCount; i++) {
        
        CGFloat value = [self.columnHeight[i] doubleValue];
        if (maxHeight < value) {
            
            maxHeight = value;
        }
    }
    return CGSizeMake(0, maxHeight+self.defaultEdgeInsets.bottom);
}

到此,瀑布流的效果就出來了.
但是可以想到,這樣來搭建布局,瀑布流的列數(shù),cell與cell之間的間距以及邊緣距就固定了,顯然這是不夠靈活的.我們應(yīng)該要把這些參數(shù)拋給使用該布局的類去決定,這樣才是一個通用的代碼.

來到布局類.h 文件中,添加協(xié)議以及代理

@class WaterFlowLayout;

@protocol WaterFlowLayoutDelegate <NSObject>

@required
//決定cell的高度,必須實(shí)現(xiàn)方法
- (CGFloat)waterFlowLayout:(WaterFlowLayout *)waterFlowLayout heightForRowAtIndex:(NSInteger)index itemWidth:(CGFloat)width;

@optional
//決定cell的列數(shù)
- (NSInteger)cloumnCountInWaterFlowLayout:(WaterFlowLayout *)waterFlowLayout;

//決定cell 的列的距離
- (CGFloat)columMarginInWaterFlowLayout:(WaterFlowLayout *)waterFlowLayout;

//決定cell 的行的距離
- (CGFloat)rowMarginInWaterFlowLayout:(WaterFlowLayout *)waterFlowLayout;

//決定cell 的邊緣距
- (UIEdgeInsets)edgeInsetInWaterFlowLayout:(WaterFlowLayout *)waterFlowLayout;

@end

@interface WaterFlowLayout : UICollectionViewLayout

/**代理*/
@property (nonatomic,assign) id <WaterFlowLayoutDelegate>delegate;

- (NSInteger)columCount;
- (CGFloat)columMargin;
- (CGFloat)rowMargin;
- (UIEdgeInsets)defaultEdgeInsets;
@end

回到布局類.m文件中,實(shí)現(xiàn)聲明的方法.在這里需要明確,外部必須通過實(shí)現(xiàn)代理給定cell的高度.另外,如果外部通過實(shí)現(xiàn)代理給定列數(shù)、列間距、行間距、邊緣距就用給定的岳掐,否則使用默認(rèn)的列數(shù)鉴竭、列間距碱鳞、行間距悼沈、邊緣距.

- (NSInteger)columCount{
    
    if ([self.delegate respondsToSelector:@selector(cloumnCountInWaterFlowLayout:)]) {
        return  [self.delegate cloumnCountInWaterFlowLayout:self];
    }
    else{
        return columCount;
    }
}

- (CGFloat)columMargin{
    
    if ([self.delegate respondsToSelector:@selector(columMarginInWaterFlowLayout:)]) {
        return  [self.delegate columMarginInWaterFlowLayout:self];
    }
    else{
        return columMargin;
    }
}

- (CGFloat)rowMargin{
    
    if ([self.delegate respondsToSelector:@selector(rowMarginInWaterFlowLayout:)]) {
        return  [self.delegate rowMarginInWaterFlowLayout:self];
    }
    else{
        return rowMargin;
    }
}

- (UIEdgeInsets)defaultEdgeInsets{
    
    if ([self.delegate respondsToSelector:@selector(edgeInsetInWaterFlowLayout:)]) {
        return  [self.delegate edgeInsetInWaterFlowLayout:self];
    }
    else{
        return defaultEdgeInsets;
    }
}

到此,CollectionView瀑布流框架搭建完成了!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末嘲叔,一起剝皮案震驚了整個濱河市懦砂,隨后出現(xiàn)的幾起案子蜒犯,更是在濱河造成了極大的恐慌,老刑警劉巖荞膘,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件罚随,死亡現(xiàn)場離奇詭異,居然都是意外死亡羽资,警方通過查閱死者的電腦和手機(jī)淘菩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來屠升,“玉大人潮改,你說我怎么就攤上這事「古” “怎么了汇在?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長脏答。 經(jīng)常有香客問我糕殉,道長亩鬼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任阿蝶,我火速辦了婚禮辛孵,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘赡磅。我一直安慰自己,他們只是感情好宝与,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布焚廊。 她就那樣靜靜地躺著,像睡著了一般习劫。 火紅的嫁衣襯著肌膚如雪咆瘟。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天诽里,我揣著相機(jī)與錄音袒餐,去河邊找鬼。 笑死谤狡,一個胖子當(dāng)著我的面吹牛灸眼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播墓懂,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼焰宣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了捕仔?” 一聲冷哼從身側(cè)響起匕积,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎榜跌,沒想到半個月后闪唆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡钓葫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年悄蕾,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瓤逼。...
    茶點(diǎn)故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡笼吟,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出霸旗,到底是詐尸還是另有隱情贷帮,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布诱告,位于F島的核電站撵枢,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锄禽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一潜必、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧沃但,春花似錦磁滚、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至淤刃,卻和暖如春晒他,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背逸贾。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工陨仅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人铝侵。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓灼伤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親哟沫。 傳聞我的和親對象是個殘疾皇子饺蔑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評論 2 361

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