一、搭建项目
使用纯代码实现瀑布流,删除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;i<self.columnCount;i++) {
colHeight[i] = 0;
colCount[i] = 0;
}
NSMutableArray * arrayM = [[NSMutableArray alloc] initWithCapacity:self.dataList.count];
NSInteger index = 0;
for (Shop * shop in self.dataList) {
//根据index 计算x,y坐标
//行数
NSInteger col = [self shortCol:colHeight];
colCount[col]++;
//x坐标
CGFloat x = self.sectionInset.left + (self.minimumInteritemSpacing + itemWidth) * col;
CGFloat y = colHeight[col];
// 计算高度,等比例缩放
// h * width/item.width
CGFloat h = [self itemSize:CGSizeMake(shop.w, shop.h) itemWidth:itemWidth];
//通过h 再计算每个item 的高度
colHeight[col] += h + self.minimumLineSpacing;
NSIndexPath *path = [NSIndexPath indexPathForItem:index inSection:0];
UICollectionViewLayoutAttributes * attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:path];
attr.frame = CGRectMake(x, y, itemWidth, h);
[arrayM addObject:attr];
index++;
}
//找到最高列
NSInteger hightCol = [self HightestCol:colHeight];
CGFloat h = (colHeight[hightCol] - colCount[hightCol] * self.minimumLineSpacing)/colCount[hightCol];
NSLog(@"%f",h);
self.itemSize = CGSizeMake(itemWidth, h);
self.layoutAttributes = arrayM;
}
//找到最大得高度,itemSize的大小应该是最大高度/这列中item的个数
-(NSInteger)HightestCol: (CGFloat *)colHeight{
CGFloat max = 0;
CGFloat col = 0;
for (int i = 0; i < self.columnCount; ++i) {
if (colHeight[i]>max) {
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]<min) {
min = colHeight[i];
col = i ;
}
}
return col;
}
//等比例 缩放
-(CGFloat)itemSize:(CGSize)size itemWidth:(CGFloat)itemWidth{
return size.height * itemWidth/ size.width;
}
/**
1.此方法返回collectionView中的所有的item
2. 当执行这个方法的时候,会计算所有 ‘ 显示 ’的item,一旦计算完成,所有的属性都会被缓存,不会再进入这个方法
3.可以提前计算出所有的itme的frame,返回返回一个items
*/
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
return self.layoutAttributes;
}
最后
在CollectionViewController中实现 数据源方法,及代理方法
#pragma mark <UICollectionViewDataSource>
-(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];
});
}
}