使用UICollectionView实现瀑布流

一、搭建项目

使用纯代码实现瀑布流,删除Main.storyboard、viewController.h 、viewController.m文件。创建新的文件CollectionViewController.m/.h文件,继承自UICollectionViewController

二、设置collectionViewController

使用纯代码创建collectionViewController需要手动设置布局方式

1.声明变量

@property(nonatomic,strong) UICollectionViewFlowLayout * layout;

2.实现布局,重写初始化方法

-(instancetype) init{
self.layout = [[UICollectionViewFlowLayout alloc] init];
if (self = [super initWithCollectionViewLayout:self.layout]) {
}
return self;
}

3.设置数据

导入plist文件,创建数据模型,使用kvc进行赋值

@interface Shop : NSObject
@property(nonatomic,copy) NSString *img;
@property(nonatomic,copy)NSString *price;     
@property(nonatomic,assign) float h;
@property(nonatomic,assign) float w;
+(instancetype) shopWithDict:(NSDictionary *) dict;
/// 通过index获取数据内容,由于数据有限,使用循环显示的方式
+(NSArray *) shopsWithIndex:(NSInteger)index;
@end

.m文件

//  KVC赋值
   (instancetype) shopWithDict:(NSDictionary *) dict{
Shop * shop = [[self alloc] init];
[shop setValuesForKeysWithDictionary:dict];
return  shop;
}
//懒加载 通过index 索引 懒加载数据
 -(NSArray *) shopsWithIndex:(NSInteger)index
{
// 获取plist 文件
//如果传入的index 不是在1、2、3 会导致程序崩溃,所以将index % 3 + 1 保证 能够找到plist 文件
NSString *fileName = NSString stringWithFormat:@"%zd.plist", index % 3 + 1];
//在程序中存放的资源,都是bundle中
//获取bundle目录
NSString *pathFile = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
//将pathFile中的内容存放到数组中
NSArray *array = [NSArray arrayWithContentsOfFile:pathFile];
 //字典转模型
NSMutableArray *arrayM =[NSMutableArray arrayWithCapacity:array.count];
for (NSDictionary * dict  in array) {
    [arrayM addObject:[self shopWithDict:dict]];
}
return  [arrayM copy];
}

controller中添加两个属性,通过索引获取数据

@property(nonatomic,strong)NSMutableArray *shops;
@property(nonatomic,assign)NSInteger index;

viewDidload方法中设置数据

[self.shops addObjectsFromArray:[Shop shopsWithIndex:self.index]];
self.index++;

导入SDWebImage框架,自定义cell,实现cell 的布局
.h

@class Shop;
@interface CollectionViewCell : UICollectionViewCell
@property(nonatomic,weak) UIImageView *img;
@property(nonatomic,weak) UILabel *price;
@property(nonatomic,strong) Shop *shop;
@end

.m

// collectionView的默认初始化方法
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
    //布局,设计UI
    [self setupUI];
}
return self;
}
-(void)setupUI{
UIImageView *imgView = [[UIImageView alloc] init];
self.img = imgView;
[self addSubview:self.img];
UIView *vi = [[UIView alloc] init];
vi.alpha = 0.4;
vi.backgroundColor = [UIColor whiteColor];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 44)];
self.price = label;
[self addSubview:vi];
[vi addSubview:self.price];
//自动布局
imgView.translatesAutoresizingMaskIntoConstraints = NO;
imgView.translatesAutoresizingMaskIntoConstraints = NO;
vi.translatesAutoresizingMaskIntoConstraints = NO;
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[imgView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imgView)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[imgView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(imgView)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[vi]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(vi)]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[vi(44)]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(vi)]];
}

目前,全部都是在对UI进行设计,UI的最后一不就是对cell在controller中布局,自定义CollectionViewFlowLayout ,设置间距

@interface CollectionViewFlowLayout : UICollectionViewFlowLayout
    @property(nonatomic,assign) NSInteger columnCount;
    @property(nonatomic,strong) NSArray *dataList;
@end

设置Layout属性

-(void)loadData{
[self.shops addObjectsFromArray:[Shop shopsWithIndex:self.index]];
self.index++;
self.layout.minimumInteritemSpacing = 5;
self.layout.minimumLineSpacing = 5;
self.layout.columnCount = 3;
self.layout.dataList = self.shops;
self.collectionView.contentInset = UIEdgeInsetsMake(0, 5, 0, 5);
}

实现layout类,设计item的大小

/*
 *布局cell
 */
/**
准备布局,只要collectionView的布局发生了改变,就会调用此方法
注意:布局的准备,不是布局
*/
-(void)prepareLayout
{
//在准备布局中,完成frame的计算,然后给layoutAttributesForElementsInRect,计算cell宽度
//1.计算么cell宽度
//在cell中设置一行显示的个数,通过个数,确定宽度
CGFloat contentWidth = self.collectionView.bounds.size.width - self.collectionView.contentInset.left * 2 - self.minimumInteritemSpacing * (self.columnCount - 1);
CGFloat itemwidth = contentWidth / self.columnCount;
//2.计算cell 的高度,设置frame
[self attribute:itemwidth];
}

// 计算cell 的frame
-(void)attribute:(CGFloat)itemWidth{
//每一个attribute 的宽度都是相同的,但是高度却不一定相同,所以需要单独的计算每一个item的高度
//使用数组,记录一行 最后一个item的最大高度
CGFloat colHeight[self.columnCount];
NSInteger colCount[self.columnCount];
for (int i = 0;imax) {
        max = colHeight[i];
        col = i;
    }
}
return  col;
}
// 找到最矮的那个col
-(NSInteger)shortCol:(CGFloat *)colHeight{
CGFloat min = MAXFLOAT;
NSInteger col = 0;
for (int  i = 0; i < self.columnCount ; ++i) {
    if (colHeight[i] *)layoutAttributesForElementsInRect:(CGRect)rect
{
return self.layoutAttributes;
}

最后
在CollectionViewController中实现 数据源方法,及代理方法

#pragma mark 
-(NSInteger)collectionView:(UICollectionView *)collectionView     numberOfItemsInSection:(NSInteger)section {

return self.shops.count;
}  

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
cell.shop = self.shops[indexPath.item];
cell.backgroundColor = [UIColor redColor];
return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
return CGSizeMake(367, 50);
}
//添加追加视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
if (kind == UICollectionElementKindSectionFooter) {
    
        self.footer  = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
    UISwitch *switch1 = [UISwitch new];
    switch1.center = self.footer.center;
    [self.footer addSubview:switch1];

//        self.footer.backgroundColor = [UIColor whiteColor];
    return self.footer;
}
return nil;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.footer == nil || self.loading) {
    return;
}
if (scrollView.contentOffset.y + scrollView.bounds.size.height > self.footer.frame.origin.y) {
    NSLog(@"开始刷新");
    self.loading = YES;
    [self.footer.indicator startAnimating];
    //模拟 数据刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadData];
        self.footer = nil;
        self.loading = NO;
        [self.footer.indicator stopAnimating];
    });
    
}
}

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