UICollectionView实现瀑布流框架

瀑布流.gif

基于完全自定义UICollectionViewLayout

#import "ViewController.h"
#import "GZDPhoto.h"
#import "GZDPhotoCell.h"
#import "GZDWaterFlowLayout.h"
//cellID
static NSString *const GZDCellID = @"photo";

@interface ViewController ()
//将collectionView作为属性
@property (weak,nonatomic) UICollectionView *collectionView;

/** 数据商品数组 */
@property (strong,nonatomic) NSMutableArray * photos;
@end

@implementation ViewController

#pragma mark - 懒加载
//图片数组为从plist中加载
- (NSMutableArray *)photos {
    if (!_photos) {
        _photos =[GZDPhoto mj_objectArrayWithFile:[[NSBundle mainBundle] pathForResource:@"1.plist" ofType:nil]];
    }
    return _photos;
}

#pragma mark - 私有方法
- (void)viewDidLoad {
    [super viewDidLoad];
    //设置collectionView和做一些基本的配置
    [self setupCollectionView];
//设置刷新控件,模拟下拉刷新和上拉加载更多
    [self setupRefresh];   
}

//设置collectionView
- (void)setupCollectionView {
    //创建布局
#布局属性完全继承于UICollectionViewLayout基类
    GZDWaterFlowLayout *layout = [[GZDWaterFlowLayout alloc] init];
  //设置布局代理
    layout.delegate = self;
    //创建collectionView大小与控制器view的大小一致
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    //设置背景颜色
    collectionView.backgroundColor = [UIColor whiteColor];
    //注册自定义cell,cell为从xib中描述
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GZDPhotoCell class]) bundle:nil] forCellWithReuseIdentifier:GZDCellID];
    //设置数据源
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
}
#pragma mark - 

- (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 - 
## waterFlow代理方法 这个方法为@required 必须实现,模型来源于控制器,所以控制器清楚每1个item的大小.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    GZDPhoto *photo = self.photos[indexPath.item];
//根据比例计算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
UICollectionView实现瀑布流框架_第1张图片
Snip20160325_1.png

UICollectionView实现瀑布流框架_第2张图片
瀑布流.png

WaterFlowLayout.h文件

#import 

@class GZDWaterFlowLayout;

##模仿tableview 使用代理来设计接口,达到解耦和,从外界控制布局内部的改变的目的
@protocol GZDWaterFlowLayoutDelegate 

@required
#必须实现的方法,返回item的行高.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath;
@optional
//控制列数
- (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 
delegate;

@end

WaterFlowLayout.m文件


#import "GZDWaterFlowLayout.h"
/** 默认的列数 */
static CGFloat const GZDWaterFlowCols = 3;
/** 默认的边距 */
static CGFloat const GZDWaterFlowPadding = 10;
/** 默认的边距 */
static CGFloat const GZDWaterFolwMargin = 10;
/** 默认的四边距 */
static UIEdgeInsets const GZDWaterFlowEdgeInsets = {10,10,10,10};

@interface GZDWaterFlowLayout ()
/** 属性数组 */
@property (strong,nonatomic) NSMutableArray * attributeses;
/** 行高数组 */
@property (strong,nonatomic) NSMutableArray * colHeights;
//getter方法声明
- (NSUInteger)cols;
- (CGFloat)margin;
- (CGFloat)padding;
- (UIEdgeInsets)edgeInsets;

@end

@implementation GZDWaterFlowLayout

#pragma mark - getter方法实现
- (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 {//属性数组
    if (!_attributeses) {
        _attributeses = [NSMutableArray array];
    }
    return _attributeses;
}

- (NSMutableArray *)colHeights {//行高数组
    if (!_colHeights) {
        _colHeights = [NSMutableArray array];
    }
    return _colHeights;
}
/** 做一些准备,在初始化的时候只会调一次,重新刷新时候会调用该方法 */
- (void)prepareLayout {
    //一定要调super
    [super prepareLayout];
//移除所有的行高元素,需要重新算一遍
    [self.colHeights removeAllObjects];
//添加默认的元素,即默认行高是顶部的间距
    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++) {
        //创建indexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        //创建indexPath处的布局元素
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        //添加进布局元素数组
        [self.attributeses addObject:attributes];
    }
    
    
}

//返回布局元素数组,有多少个item就有多少个布局元素 --如果继承自最初始的布局时 调用非常的频繁,所以在prepareLayout方法中计算布局属性
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attributeses;
}

##返回indexPath位置的布局元素  -- 核心代码

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //最短的那一行的行数
    NSInteger minColNum = 0;
    //最短的那一行的行高
    CGFloat minColHeight = MAXFLOAT;
    //遍历行高数组
    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;
    //由于是必须实现的方法所以不需要判断
    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);
    //更新行高数组
    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

你可能感兴趣的:(UICollectionView实现瀑布流框架)