CollectionView的详细使用(四)

本人小白,欢迎各位大佬补充指点

自定义布局-瀑布流

实现瀑布流常见的3中方案:
1.view上面添加一个scrollView,接着在添加3列tableView,分别禁止tableView的滚动
2.view上面添加一个scrollView,在一个一个往scrollView上面添加
3.用UIConllectionView
分析可得:瀑布流总是找最短的那个添加,因此不是流水布局,那么自定义布局就要继承自根布局

控制器代码如下:

#import "ZHWaterLayout.h"
#import "ViewController3.h"
#import "ZHShopViewCell.h"
#import "MJRefresh.h"
#import "ZHShop.h"
#import "MJExtension.h"
@interface ViewController3 ()<UICollectionViewDataSource,ZHWaterLayoutDelegate>
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,weak) UICollectionView *collectionView;
@end
static NSString * const cellID = @"shopcell";

@implementation ViewController3
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray ;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupLayout];
    [self setupRefresh];
}
-(void)setupRefresh{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(newData)];
    [self.collectionView.header beginRefreshing];
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(moreData)];
    self.collectionView.footer.hidden = YES;
}
-(void)newData{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSArray *aray = [ZHShop objectArrayWithFilename:@"112.plist"];
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:aray];
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
    });
   
}
-(void)moreData{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSArray *aray = [ZHShop objectArrayWithFilename:@"112.plist"];
        [self.dataArray addObjectsFromArray:aray];
        [self.collectionView reloadData];
        [self.collectionView.footer endRefreshing];
    });
    
}
-(void)setupLayout{
    ZHWaterLayout *layout = [[ZHWaterLayout alloc] init];
    layout.delegate = self;
    UICollectionView *collection = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    //只能注册
    [collection registerNib:[UINib nibWithNibName:@"ZHShopViewCell" bundle:nil] forCellWithReuseIdentifier:cellID];
    collection.backgroundColor = [UIColor whiteColor];
    collection.dataSource = self;
    self.collectionView = collection;
    [self.view addSubview:collection];
}

#pragma mark - UICollectionViewDataSource
//必须实现@required:
//每个section里面有多少个item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    self.collectionView.footer.hidden = self.dataArray.count == 0;
    return self.dataArray.count;
}

//每个cell
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZHShopViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    item.shop = self.dataArray[indexPath.item];
    return item;
}
#pragma mark - ZHWaterLayoutDelegate
-(CGFloat)waterLayout:(ZHWaterLayout *)waterLayout heightForItemAtIndex:(NSInteger )index andItemWidth:(CGFloat)itemWidth{
    ZHShop *shop = self.dataArray[index];
    return itemWidth * shop.h/shop.w;
}
-(NSInteger)columCountWaterLayout:(ZHWaterLayout *)waterLayout{
    return 4;
}
-(CGFloat)columMarginWaterLayout:(ZHWaterLayout *)waterLayout{
    return 10;
}
-(CGFloat)rowMarginWaterLayout:(ZHWaterLayout *)waterLayout{
    return 10;
}
-(UIEdgeInsets)edgeInsetsWaterLayout:(ZHWaterLayout *)waterLayout{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
@end

自定义xib的cell代码如下:

#import <UIKit/UIKit.h>
@class ZHShop;
@interface ZHShopViewCell : UICollectionViewCell
@property (nonatomic, strong) ZHShop *shop;
@end
#import "ZHShopViewCell.h"
#import "ZHShop.h"
#import "UIImageView+WebCache.h"
@interface ZHShopViewCell()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@end
@implementation ZHShopViewCell

- (void)setShop:(ZHShop *)shop
{
    _shop = shop;
    // 1.图片
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:shop.img] placeholderImage:[UIImage imageNamed:@"loading"]];
    // 2.价格
    self.priceLabel.text = shop.price;
}
@end

模型ZHShop如下:

#import <UIKit/UIKit.h>

@interface ZHShop : NSObject
@property (nonatomic, assign) CGFloat w;
@property (nonatomic, assign) CGFloat h;
@property (nonatomic, copy) NSString *img;
@property (nonatomic, copy) NSString *price;
@end

自定义布局ZHWaterLayout如下:

#import <UIKit/UIKit.h>
@class ZHWaterLayout;
//自定义协议
@protocol ZHWaterLayoutDelegate<NSObject>
@required
/**
 返回item的高度
 */
-(CGFloat)waterLayout:(ZHWaterLayout *)waterLayout heightForItemAtIndex:(NSInteger )index andItemWidth:(CGFloat)itemWidth;
@optional
/**
 有多少列
 */
-(NSInteger)columCountWaterLayout:(ZHWaterLayout *)waterLayout;
/**
列边距
 */
-(CGFloat)columMarginWaterLayout:(ZHWaterLayout *)waterLayout;
/**
行间距
 */
-(CGFloat)rowMarginWaterLayout:(ZHWaterLayout *)waterLayout;
/**
 内边距
 */
-(UIEdgeInsets )edgeInsetsWaterLayout:(ZHWaterLayout *)waterLayout;
@end
@interface ZHWaterLayout : UICollectionViewLayout
@property (nonatomic,weak) id<ZHWaterLayoutDelegate> delegate;
@end
#import "ZHWaterLayout.h"

@interface ZHWaterLayout()
@property (nonatomic,strong) NSMutableArray *attriArray;
//用来存放所有列的高度
@property (nonatomic,strong) NSMutableArray *colsHeght;
//注意get方法要想提示写出,必须在这里先声明!!!!
-(CGFloat)rowMargin;
-(CGFloat)columMargin;
-(NSInteger)columCount;
-(UIEdgeInsets)edgeInsets;

@end
//默认值
static const CGFloat rowMargin = 10;//行距
static const CGFloat colMargin = 10;//列距
static const NSInteger col = 3;//默认列数
static const UIEdgeInsets edgeInsets = {10,10,10,10};//内边距

@implementation ZHWaterLayout
//数据处理get方法
-(CGFloat)rowMargin{
    if ([self.delegate respondsToSelector:@selector(rowMarginWaterLayout:)]) {
        return [self.delegate rowMarginWaterLayout:self];
    }else{
        return rowMargin;
    }
}
-(CGFloat)columMargin{
    if ([self.delegate respondsToSelector:@selector(columMarginWaterLayout:)]) {
        return [self.delegate columMarginWaterLayout:self];
    }else{
        return colMargin;
    }
}
-(NSInteger)columCount{
    if ([self.delegate respondsToSelector:@selector(columCountWaterLayout:)]) {
        return [self.delegate columCountWaterLayout:self];
    }else{
        return col;
    }
}
-(UIEdgeInsets)edgeInsets{
    if ([self.delegate respondsToSelector:@selector(edgeInsetsWaterLayout:)]) {
        return [self.delegate edgeInsetsWaterLayout:self];
    }else{
       return edgeInsets;
    }
}
//记录各列的高度
-(NSMutableArray *)colsHeght{
    if (_colsHeght == nil) {
        _colsHeght = [NSMutableArray array];
    }
    return _colsHeght ;
}
//存储所有cell的UICollectionViewLayoutAttributes
-(NSMutableArray *)attriArray{
    if (_attriArray == nil) {
        _attriArray = [NSMutableArray array];
    }
    return _attriArray ;
}
//初始化操作
-(void)prepareLayout{
    [super prepareLayout];
    //1.每次刷新就回重新布局一次,重新清理一下数据
    //1.1清除高度数组并初始化
    [self.colsHeght removeAllObjects];
    //初始化数组
    for (int i= 0; i<self.columCount; i++) {
        [self.colsHeght addObject:@(self.edgeInsets.top)];
    }
    //1.2清除布局属性数据
    [self.attriArray removeAllObjects];
    //2.计算出所有cell的UICollectionViewLayoutAttributes
    //共多少个item
    NSInteger rowcount = [self.collectionView numberOfItemsInSection:0];
    //遍历计算出每一个
    for (int i = 0 ; i<rowcount; i++) {
        //创建UICollectionViewLayoutAttributes
        NSIndexPath *indexpath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *attri = [self layoutAttributesForItemAtIndexPath:indexpath];
        //添加UICollectionViewLayoutAttributes到数组中
        [self.attriArray addObject:attri];
    }
}
//返回rect内的所有cell的UICollectionViewLayoutAttributes数组
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.attriArray;
}

//返回每一个cell的UICollectionViewLayoutAttributes
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    //1.创建UICollectionViewLayoutAttributes对象
    UICollectionViewLayoutAttributes *attri = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //2.设置UICollectionViewLayoutAttributes的frame属性
    CGFloat collectW = self.collectionView.frame.size.width;
    //2.1计算出宽度
    CGFloat width = (collectW-self.edgeInsets.left-self.edgeInsets.right-(self.columCount-1)*self.columMargin)/self.columCount;
    //2.2根据外部模型数据传进来的高度计算出高度
    CGFloat height = [self.delegate waterLayout:self heightForItemAtIndex:indexPath.item andItemWidth:width];
    //2.3 计算出x
    //找出高度最短的那一列
//    __block NSUInteger desCol = 0;
//   __block CGFloat minColHeight = MAXFLOAT;
//    [self.colsHeght enumerateObjectsUsingBlock:^(NSNumber *  _Nonnull colHeight, NSUInteger idx, BOOL * _Nonnull stop) {
//        if (colHeight.doubleValue < minColHeight) {
//            minColHeight = colHeight.doubleValue;
//            desCol = idx;
//        }
//    }];
    //这样遍历可以少算一列
    NSInteger desCol = 0;
    CGFloat minColHeight = [self.colsHeght[0] doubleValue];
    for (NSInteger i = 1; i<self.columCount; i++) {
        //获取第一列的高度
        CGFloat colH = [self.colsHeght[i] doubleValue];
        if (colH<minColHeight) {
            minColHeight = colH;
            desCol = i;
        }
    }
    CGFloat x = self.edgeInsets.left + desCol*(width + self.columMargin);
    //2.4计算出y值
    CGFloat y = minColHeight;//第一行时不加rowmargin
    if (y != self.edgeInsets.top) {
        y += self.rowMargin;
    }
    //3.赋值frame
    attri.frame = CGRectMake(x,y, width, height);
    //4.更新高度数组
    self.colsHeght[desCol] =@(CGRectGetMaxY(attri.frame)) ;
    return attri;
}

//返回collectionView的contentsize
-(CGSize)collectionViewContentSize{
    CGFloat maxColHeight = [self.colsHeght[0] doubleValue];
    for (NSInteger i = 1; i<self.columCount
         ; i++) {
        //获取第一列的高度
        CGFloat colH = [self.colsHeght[i] doubleValue];
        if (colH>maxColHeight) {
            maxColHeight = colH;
        }
    }
    return CGSizeMake(0, maxColHeight+self.edgeInsets.bottom);
}

@end

demo的Github地址

效果图如下:

2.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,204评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,091评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,548评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,657评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,689评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,554评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,302评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,216评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,661评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,851评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,977评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,697评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,306评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,898评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,019评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,138评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,927评论 2 355

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,103评论 4 62
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,135评论 25 707
  • 1. 前几天忽然看到自己年末时写的一篇文章,为了应“过年回家被相亲”的景,写了一篇《我不着急恋爱,我想变得更好一点...
    离离离离离晨阅读 534评论 9 16
  • 做微商不要总是想着别人可以带给你什么! 要多想想自己可以带给别人什么! 做微商不要把利益放在第一位!要把人情放在第...
    筱雅的致雅阅读 192评论 0 0
  • (≧∇≦)/
    5d626066ce21阅读 85评论 0 0