華山論劍之淺談iOS瀑布流

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

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

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

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

3.UICollectionView實現瀑布流就是對UICollectionView的FlowLayout重寫.



UICollectionView 實現瀑布流

瀑布流的實現,現在大多數人都是使用集合視圖 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;

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

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

// 列數
@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的數量
@property (nonatomic,assign)NSUInteger numberOfItems;

// 這是一個數組,保存每一列的高度
@property (nonatomic,strong)NSMutableArray *columnHeights;
// 這是一個數組,數組中保存的是一種類型,這種類型決定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。并放入數組
-(void)prepareLayout{
    [super prepareLayout];
    
    // 循環添加top高度
    for (int i = 0; i < self.numberOfColumn; i++) {
        self.columnHeights[i] = @(self.sectionInsets.top);
    }
    
    // 獲取item數量
    self.numberOfItems = [self.collectionView numberOfItemsInSection:0];
    
    // 循環計算每一個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);
        
        // 放入數組
        [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的位置和大小(數組)
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.itemAttributes;
}



@end

接下來我們就在我們需要的地方調用我們已經封裝好的類和實現協議方法就可以了.這里我在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;//創建可變數組,存儲json文件數據

@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設置集合視圖的flowLayout,我們要做的就是新創建一個繼承于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;
    // 內邊距
    flowLayout.sectionInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    // 列數
    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 就是測試用的,

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

推薦閱讀更多精彩內容

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