华山论剑之浅谈iOS瀑布流

心灵鸡汤可不是谁想喝就喝的! --------------栋哥

看完千篇一律的UI布局之后,当我们看到瀑布流的布局是不是觉得有种耳目一新的感觉呢?今天我们就说一下如果实现瀑布流,对于瀑布流,现在iOS中总共存在着三种实现方法.

1.实现瀑布流的布局,我们需要计算每一张图片的尺寸大小,然后根据列数布局到我们的UIScrollView上去

华山论剑之浅谈iOS瀑布流_第1张图片

2.UITableView实现瀑布流效果,就是每一列都是一个视图.

华山论剑之浅谈iOS瀑布流_第2张图片

3.UICollectionView实现瀑布流就是对UICollectionView的FlowLayout重写.

华山论剑之浅谈iOS瀑布流_第3张图片


UICollectionView 实现瀑布流

瀑布流的实现,现在大多数人都是使用集合视图 UICollectionView 这个类做的,我们需要把集合视图的布局进行重新定义.

对于UICollectionViewFlowLayout 这里有个封装好的类,有需要的可以直接拿去使用了

WaterfallLayout.h文件中.

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

#import 

@protocol WaterfallLayoutDelegate 

// 获取图片高度
- (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)iddelegate;


@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 *)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 ()

@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下载

你可能感兴趣的:(华山论剑之浅谈iOS瀑布流)