UICollectionView實(shí)現(xiàn)瀑布流框架

瀑布流.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;

/** 數(shù)據(jù)商品數(shù)組 */
@property (strong,nonatomic) NSMutableArray * photos;
@end

@implementation ViewController

#pragma mark - 懶加載
//圖片數(shù)組為從plist中加載
- (NSMutableArray *)photos {
    if (!_photos) {
        _photos =[GZDPhoto mj_objectArrayWithFile:[[NSBundle mainBundle] pathForResource:@"1.plist" ofType:nil]];
    }
    return _photos;
}

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

//設(shè)置collectionView
- (void)setupCollectionView {
    //創(chuàng)建布局
#布局屬性完全繼承于UICollectionViewLayout基類
    GZDWaterFlowLayout *layout = [[GZDWaterFlowLayout alloc] init];
  //設(shè)置布局代理
    layout.delegate = self;
    //創(chuàng)建collectionView大小與控制器view的大小一致
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    //設(shè)置背景顏色
    collectionView.backgroundColor = [UIColor whiteColor];
    //注冊(cè)自定義cell,cell為從xib中描述
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([GZDPhotoCell class]) bundle:nil] forCellWithReuseIdentifier:GZDCellID];
    //設(shè)置數(shù)據(jù)源
    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代理方法 這個(gè)方法為@required 必須實(shí)現(xiàn),模型來(lái)源于控制器,所以控制器清楚每1個(gè)item的大小.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath {
    GZDPhoto *photo = self.photos[indexPath.item];
//根據(jù)比例計(jì)算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 使用代理來(lái)設(shè)計(jì)接口,達(dá)到解耦和,從外界控制布局內(nèi)部的改變的目的
@protocol GZDWaterFlowLayoutDelegate <NSObject>

@required
#必須實(shí)現(xiàn)的方法,返回item的行高.
- (CGFloat)waterFlowLayout:(GZDWaterFlowLayout *)waterFlowLayout itemWidth:(CGFloat)itemWidth heightForItemAtIndexPath:(NSIndexPath *)indexPath;
@optional
//控制列數(shù)
- (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"
/** 默認(rèn)的列數(shù) */
static CGFloat const GZDWaterFlowCols = 3;
/** 默認(rèn)的邊距 */
static CGFloat const GZDWaterFlowPadding = 10;
/** 默認(rèn)的邊距 */
static CGFloat const GZDWaterFolwMargin = 10;
/** 默認(rèn)的四邊距 */
static UIEdgeInsets const GZDWaterFlowEdgeInsets = {10,10,10,10};

@interface GZDWaterFlowLayout ()
/** 屬性數(shù)組 */
@property (strong,nonatomic) NSMutableArray * attributeses;
/** 行高數(shù)組 */
@property (strong,nonatomic) NSMutableArray * colHeights;
//getter方法聲明
- (NSUInteger)cols;
- (CGFloat)margin;
- (CGFloat)padding;
- (UIEdgeInsets)edgeInsets;

@end

@implementation GZDWaterFlowLayout

#pragma mark - getter方法實(shí)現(xiàn)
- (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 {//屬性數(shù)組
    if (!_attributeses) {
        _attributeses = [NSMutableArray array];
    }
    return _attributeses;
}

- (NSMutableArray *)colHeights {//行高數(shù)組
    if (!_colHeights) {
        _colHeights = [NSMutableArray array];
    }
    return _colHeights;
}
/** 做一些準(zhǔn)備,在初始化的時(shí)候只會(huì)調(diào)一次,重新刷新時(shí)候會(huì)調(diào)用該方法 */
- (void)prepareLayout {
    //一定要調(diào)super
    [super prepareLayout];
//移除所有的行高元素,需要重新算一遍
    [self.colHeights removeAllObjects];
//添加默認(rèn)的元素,即默認(rèn)行高是頂部的間距
    for (NSInteger i = 0; i < self.cols; i++) {
        [self.colHeights addObject:@(self.edgeInsets.top)];
    }
    //移除所有的布局元素
    [self.attributeses removeAllObjects];
    //只需要計(jì)算一次
    for (NSInteger i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        //創(chuàng)建indexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        //創(chuàng)建indexPath處的布局元素
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        //添加進(jìn)布局元素?cái)?shù)組
        [self.attributeses addObject:attributes];
    }
    
    
}

//返回布局元素?cái)?shù)組,有多少個(gè)item就有多少個(gè)布局元素 --如果繼承自最初始的布局時(shí) 調(diào)用非常的頻繁,所以在prepareLayout方法中計(jì)算布局屬性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attributeses;
}

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

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //最短的那一行的行數(shù)
    NSInteger minColNum = 0;
    //最短的那一行的行高
    CGFloat minColHeight = MAXFLOAT;
    //遍歷行高數(shù)組
    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;
    //由于是必須實(shí)現(xiàn)的方法所以不需要判斷
    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);
    //更新行高數(shù)組
    self.colHeights[minColNum] = @(CGRectGetMaxY(attributes.frame));
    return attributes;
}
//返回contentSize
- (CGSize)collectionViewContentSize {
    //遍歷取出最大的那一個(gè)行高
    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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,211評(píng)論 4 61
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,983評(píng)論 25 709
  • 暮色的云,等不來(lái)想要等的人。小深:十八歲,雙魚(yú)女,偶爾寫(xiě)字讀詩(shī),立黃昏的小徒弟。立黃昏:二十二歲,雙魚(yú)男,偶爾吃飯...
    立黃昏閱讀 1,216評(píng)論 57 37
  • 夜永遠(yuǎn)等待綻放黎明 在喧囂之后 落入沉靜 光漸漸充盈著 無(wú)所謂星辰與海洋 無(wú)懼于困難與悲傷 像站在懸崖上的極限挑戰(zhàn)...
  • 四圣諦:苦集滅道 五蘊(yùn) 色蘊(yùn):包括自身的眼、耳、鼻、舌、身等五根,以及反映自身而起感受作用的色、聲、香、味、觸的五...
    monchhichi1005閱讀 515評(píng)論 0 0

友情鏈接更多精彩內(nèi)容