UICollectionView實現瀑布流框架

瀑布流.gif

基于完全自定義UICollectionViewLayout

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

@interface ViewController ()<UICollectionViewDataSource,GZDWaterFlowLayoutDelegate>
//將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 - <UICollectionViewDataSource>

- (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 - <GZDWaterFlowLayoutDelegate>
## 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
Snip20160325_1.png

瀑布流.png

WaterFlowLayout.h文件

#import <UIKit/UIKit.h>

@class GZDWaterFlowLayout;

##模仿tableview 使用代理來設計接口,達到解耦和,從外界控制布局內部的改變的目的
@protocol GZDWaterFlowLayoutDelegate <NSObject>

@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<GZDWaterFlowLayoutDelegate> 
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<UICollectionViewLayoutAttributes *> *)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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,180評論 4 61
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,820評論 25 708
  • 暮色的云,等不來想要等的人。小深:十八歲,雙魚女,偶爾寫字讀詩,立黃昏的小徒弟。立黃昏:二十二歲,雙魚男,偶爾吃飯...
    立黃昏閱讀 1,069評論 57 37
  • 夜永遠等待綻放黎明 在喧囂之后 落入沉靜 光漸漸充盈著 無所謂星辰與海洋 無懼于困難與悲傷 像站在懸崖上的極限挑戰...
    寫作的沐陽愛畫畫閱讀 188評論 0 1
  • 四圣諦:苦集滅道 五蘊 色蘊:包括自身的眼、耳、鼻、舌、身等五根,以及反映自身而起感受作用的色、聲、香、味、觸的五...
    monchhichi1005閱讀 393評論 0 0