華山論劍之淺談iOS瀑布流

心靈雞湯可不是誰想喝就喝的! --------------棟哥

看完千篇一律的UI布局之后,當我們看到瀑布流的布局是不是覺得有種耳目一新的感覺呢?今天我們就說一下如果實現(xiàn)瀑布流,對于瀑布流,現(xiàn)在iOS中總共存在著三種實現(xiàn)方法.

1.實現(xiàn)瀑布流的布局,我們需要計算每一張圖片的尺寸大小,然后根據(jù)列數(shù)布局到我們的UIScrollView上去

2.UITableView實現(xiàn)瀑布流效果,就是每一列都是一個視圖.

3.UICollectionView實現(xiàn)瀑布流就是對UICollectionView的FlowLayout重寫.



UICollectionView 實現(xiàn)瀑布流

瀑布流的實現(xiàn),現(xiàn)在大多數(shù)人都是使用集合視圖 UICollectionView 這個類做的,我們需要把集合視圖的布局進行重新定義.

對于UICollectionViewFlowLayout 這里有個封裝好的類,有需要的可以直接拿去使用了

WaterfallLayout.h文件中.

//
//  WaterfallLayout.h
//  Abe的瀑布流的封裝
//
//  Created by dongge on 16/3/2.
//  Copyright ? 2016年 Abe. All rights reserved.
//

#import <UIKit/UIKit.h>

@protocol WaterfallLayoutDelegate <NSObject>

// 獲取圖片高度
- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath;

@end


@interface WaterfallLayout : UICollectionViewFlowLayout

// item大小
@property (nonatomic,assign)CGSize itemSize;

// 內(nèi)邊距
@property (nonatomic,assign)UIEdgeInsets sectionInsets;

// 間距
@property (nonatomic,assign)CGFloat insertItemSpacing;

// 列數(shù)
@property (nonatomic,assign)NSUInteger numberOfColumn;

// 代理(提供圖片高度)
@property (nonatomic,weak)id<WaterfallLayoutDelegate>delegate;


@end

WaterfallLayout.m中

//
//  WaterfallLayout.m
//  Abe的瀑布流的封裝
//
//  Created by dongge on 16/3/2.
//  Copyright ? 2016年 Abe. All rights reserved.
//

#import "WaterfallLayout.h"


@interface WaterfallLayout()


// 所有Item的數(shù)量
@property (nonatomic,assign)NSUInteger numberOfItems;

// 這是一個數(shù)組反症,保存每一列的高度
@property (nonatomic,strong)NSMutableArray *columnHeights;
// 這是一個數(shù)組茬贵,數(shù)組中保存的是一種類型,這種類型決定item的位置和大小姥饰。
@property (nonatomic,strong)NSMutableArray *itemAttributes;
// 獲取最長列索引
- (NSInteger)indexForLongestColumn;
// 獲取最短列索引
- (NSInteger)indexForShortestColumn;


@end

@implementation WaterfallLayout


- (NSMutableArray *)columnHeights{
    if (nil == _columnHeights) {
        self.columnHeights = [NSMutableArray array];
    }
    return _columnHeights;
}

-(NSMutableArray *)itemAttributes{
    if (nil == _itemAttributes) {
        self.itemAttributes = [NSMutableArray array];
    }
    return _itemAttributes;
}


// 獲取最長列索引
- (NSInteger)indexForLongestColumn{
    // 記錄索引
    NSInteger longestIndex = 0;
    // 記錄當前最長列高度
    CGFloat longestHeight = 0;
    for (int i = 0; i < self.numberOfColumn; i++) {
        // 取出列高度
        CGFloat currentHeight = [self.columnHeights[i] floatValue];
        // 判斷
        if (currentHeight > longestHeight) {
            longestHeight = currentHeight;
            longestIndex = i;
        }
    }
    return longestIndex;
    
}
// 獲取最短列索引
- (NSInteger)indexForShortestColumn{
    
    // 記錄索引
    NSInteger shortestIndex = 0;
    
    // 記錄最短高度
    CGFloat shortestHeight = MAXFLOAT;
    for (int i = 0; i < self.numberOfColumn; i++) {
        
        CGFloat currentHeight = [self.columnHeights[i] floatValue];
        if (currentHeight < shortestHeight) {
            shortestHeight = currentHeight;
            shortestIndex = i;
        }
    }
    return shortestIndex;
}

// 這里計算每一個item的x,y孝治,w列粪,h。并放入數(shù)組
-(void)prepareLayout{
    [super prepareLayout];
    
    // 循環(huán)添加top高度
    for (int i = 0; i < self.numberOfColumn; i++) {
        self.columnHeights[i] = @(self.sectionInsets.top);
    }
    
    // 獲取item數(shù)量
    self.numberOfItems = [self.collectionView numberOfItemsInSection:0];
    
    // 循環(huán)計算每一個item的x,y,width,height
    for (int i = 0; i < self.numberOfItems; i++) {
        
        // x,y
        
        // 獲取最短列
        NSInteger shortIndex = [self indexForShortestColumn];
        
        // 獲取最短列高度
        CGFloat shortestH = [self.columnHeights[shortIndex] floatValue];
        
        // x
        CGFloat detalX = self.sectionInsets.left + (self.itemSize.width + self.insertItemSpacing) * shortIndex;
        
        // y
        CGFloat detalY = shortestH + self.insertItemSpacing;
        
        // h
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        CGFloat itemHeight = 0;
        if (self.delegate != nil && [self.delegate respondsToSelector:@selector(heightForItemIndexPath:)]){
            itemHeight = [self.delegate heightForItemIndexPath:indexPath];
        }
        
        // 保存item frame屬性的對象
        UICollectionViewLayoutAttributes *la = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        la.frame = CGRectMake(detalX, detalY, self.itemSize.width, itemHeight);
        
        // 放入數(shù)組
        [self.itemAttributes addObject:la];
        
        // 更新高度
        self.columnHeights[shortIndex] = @(detalY + itemHeight);
    }
}


// 計算contentSize
- (CGSize)collectionViewContentSize{
    // 獲取最高列
    NSInteger longestIndex = [self indexForLongestColumn];
    CGFloat longestH = [self.columnHeights[longestIndex] floatValue];
    
    // 計算contentSize
    CGSize contentSize = self.collectionView.frame.size;
    contentSize.height = longestH + self.sectionInsets.bottom;
    
    return contentSize;
}

// 返回所有item的位置和大小(數(shù)組)
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.itemAttributes;
}



@end

接下來我們就在我們需要的地方調(diào)用我們已經(jīng)封裝好的類和實現(xiàn)協(xié)議方法就可以了.這里我在ViewController.m中做了一下測試

//
//  ViewController.m
//  Abe的瀑布流的封裝
//
//  Created by dongge on 16/3/2.
//  Copyright ? 2016年 Abe. All rights reserved.
//

#import "ViewController.h"

#import "WaterFlowModel.h"

#import "WaterFlowCell.h"

#import "WaterfallLayout.h"

#import "UIImageView+WebCache.h"

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,WaterfallLayoutDelegate>

@property(nonatomic,strong)NSMutableArray *dataArray;//創(chuàng)建可變數(shù)組,存儲json文件數(shù)據(jù)

@end

@implementation ViewController


-(NSMutableArray *)dataArray{

    if (nil == _dataArray) {
        _dataArray = [NSMutableArray array];
    }

    return _dataArray;
    
}

//解析json文件

-(void)parserJsonData {

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"json"];

    NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
    
    NSMutableArray *arr = [NSMutableArray array ];
    
    arr = [NSJSONSerialization JSONObjectWithData:jsonData options:(NSJSONReadingAllowFragments) error:nil];
    
    for (NSDictionary *dic in arr) {
        
        WaterFlowModel *model = [[WaterFlowModel alloc]init];
        
        [model setValuesForKeysWithDictionary:dic];
        
        [self.dataArray addObject: model];
        
    }

}


//在viewDidLoad設(shè)置集合視圖的flowLayout,我們要做的就是新創(chuàng)建一個繼承于UICollectionViewLayout的類,在這個子類當中,做出瀑布流的布局.
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    WaterfallLayout *flowLayout = [[WaterfallLayout alloc] init];
    // 高度
    flowLayout.delegate = self;
    
    
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 40) / 3;
    
    flowLayout.itemSize = CGSizeMake(w, w);
    // 間隙
    flowLayout.insertItemSpacing = 10;
    // 內(nèi)邊距
    flowLayout.sectionInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    // 列數(shù)
    flowLayout.numberOfColumn = 3;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [self.view addSubview:collectionView];
    
    [collectionView registerClass:[WaterFlowCell class] forCellWithReuseIdentifier:@"cell"];
    
    
    collectionView.backgroundColor = [UIColor whiteColor];
    [self parserJsonData];
}

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

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WaterFlowCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    WaterFlowModel *m = self.dataArray[indexPath.item];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:m.thumbURL]];
    return cell;
}


// 計算高度
- (CGFloat)heightForItemIndexPath:(NSIndexPath *)indexPath{
    WaterFlowModel *m = self.dataArray[indexPath.item];
    CGFloat w = ([UIScreen mainScreen].bounds.size.width - 40) / 3;
    CGFloat h = (w * m.height) / m.width;
    return h;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

上面的WaterFlowCell 和 WaterFlowModel 就是測試用的,

總結(jié):瀑布流的實現(xiàn)原理就是當我們需要往某一行添加上新的圖片的時候,我們就先判斷那一行的長度最短,然后就添加上去即可.
--->點擊進入神經(jīng)騷棟瀑布流Demo下載
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谈飒,一起剝皮案震驚了整個濱河市岂座,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌杭措,老刑警劉巖费什,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異手素,居然都是意外死亡鸳址,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進店門泉懦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來稿黍,“玉大人,你說我怎么就攤上這事崩哩⊙睬颍” “怎么了?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵邓嘹,是天一觀的道長酣栈。 經(jīng)常有香客問我,道長汹押,這世上最難降的妖魔是什么钉嘹? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮鲸阻,結(jié)果婚禮上跋涣,老公的妹妹穿的比我還像新娘。我一直安慰自己鸟悴,他們只是感情好陈辱,可當我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著细诸,像睡著了一般沛贪。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天利赋,我揣著相機與錄音水评,去河邊找鬼。 笑死媚送,一個胖子當著我的面吹牛中燥,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播塘偎,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼疗涉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了吟秩?” 一聲冷哼從身側(cè)響起咱扣,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎涵防,沒想到半個月后闹伪,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡壮池,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年祭往,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片火窒。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖驮肉,靈堂內(nèi)的尸體忽然破棺而出熏矿,到底是詐尸還是另有隱情,我是刑警寧澤离钝,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布票编,位于F島的核電站,受9級特大地震影響卵渴,放射性物質(zhì)發(fā)生泄漏慧域。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一浪读、第九天 我趴在偏房一處隱蔽的房頂上張望昔榴。 院中可真熱鬧,春花似錦碘橘、人聲如沸互订。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽仰禽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間吐葵,已是汗流浹背规揪。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留温峭,地道東北人猛铅。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像诚镰,于是被迫代替她去往敵國和親奕坟。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,689評論 2 354

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫清笨、插件月杉、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,098評論 4 62
  • 今天在淘票票上偶然看到了這部評分高達9.7分的電影――《摔跤吧检号,爸爸》腌歉,我瞬間有點驚訝,于是便立刻訂票并懷著好奇的...
    闌珊非隅閱讀 791評論 0 5
  • 我始終認為一個人可以很天真簡單的活下去齐苛,必是身邊無數(shù)人用更大的代價守護而來的翘盖。 —— 《小王子》 ????
    杜小遙閱讀 275評論 0 0
  • 有人說:人啊玛痊,過了二十幾歲汰瘫,上帝就會開始給你做減法。拿掉你的一些朋友擂煞,拿掉你的一些夢想混弥。有些人跟你分道揚鑣...
    19畫生閱讀 8,306評論 0 2
  • 如果你忘了我 我只能說沒關(guān)系 如果你真的忘了我 我也只能說沒關(guān)系 身命中的人來了去,去了又來 而我始終忘不了 有那...
    納蘭秋琪閱讀 210評論 0 0