自定义UICollectionViewLayout之瀑布流

时间:2023-03-08 19:32:46
自定义UICollectionViewLayout之瀑布流

目标效果

自定义UICollectionViewLayout之瀑布流

因为系统给我们提供的 UICollectionViewFlowLayout 布局类不能实现瀑布流的效果,如果我们想实现 瀑布流 的效果,需要自定义一个 UICollectionViewLayout  类,实现瀑布流效果。效果如右图。

依赖工具:

我们需要一个图片大小和图片地址的Josn数据, 和 SDWebImage图片加载的第三方工具

RootViewController.m

 #import "RootViewController.h"
#import "DataModel.h"
#import "WaterFlowLayout.h"
#import "RootCell.h"
#import "UIImageView+WebCache.h" @interface RootViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, WaterFlowLayoutDelegate> // 声明大数组存放所有的数据
@property (nonatomic, strong) NSMutableArray *allDataArray; // 定义collectionView
@property (nonatomic, strong) UICollectionView *collectionView; @end @implementation RootViewController // 懒加载
- (NSMutableArray *)allDataArray {
if (!_allDataArray) {
_allDataArray = [NSMutableArray array];
}
return _allDataArray;
} - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view. // 读取数据
[self loadData]; // 初始化布局
[self initLayout]; // 注册cell
[self.collectionView registerClass:[RootCell class] forCellWithReuseIdentifier:@"cell"];
} // 初始化布局
- (void)initLayout { // 1.创建UICollectionView的布局样式对象
WaterFlowLayout *water = [[WaterFlowLayout alloc] init];
CGFloat width = ([UIScreen mainScreen].bounds.size.width - ) / ;
water.itemSize = CGSizeMake(width, width);
// 设置内边距
water.sectionInsets = UIEdgeInsetsMake(, , , );
// 设置间距
water.spacing = ;
// 设置有多少列
water.numberOfColumn = ;
// 设置代理
water.delegate = self; // 2.布局UICollectionView
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:water];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.collectionView]; } // 读取数据
- (void)loadData { // 第一步:获取文件路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"json"];
// 第二步:根据路径读取数据,转为NSData对象
NSData *data = [NSData dataWithContentsOfFile:filePath];
// 第三步:根据json格式解析数据
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil]; // NSLog(@"%@", dataArray);
// 第四步:遍历数组,将数据转为model对象
for (NSDictionary *dict in dataArray) { // 创建model对象
DataModel *model = [[DataModel alloc] init];
// 使用KVC给model赋值
[model setValuesForKeysWithDictionary:dict]; // 将model添加到大数组中
[self.allDataArray addObject:model];
}
// NSLog(@"%@", self.allDataArray);
} // 设置分区个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return ;
}
// 设置每个分区的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return self.allDataArray.count;
} // 返回每一个item的cell对象
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { RootCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; // 设置cell数据 DataModel *model = self.allDataArray[indexPath.row];
NSURL *url = [NSURL URLWithString:model.thumbURL];
[cell.photoView sd_setImageWithURL:url];
cell.backgroundColor = [UIColor orangeColor];
return cell;
} // 实现代理方法返回每一个item的高度
- (CGFloat)heightForItemAtIndexPath:(NSIndexPath *)indexPath { DataModel *model = self.allDataArray[indexPath.row];
CGFloat width = ([UIScreen mainScreen].bounds.size.width - ) / ;
// 计算item高度
CGFloat height = model.height / model.width * width;
return height; } @end

主视图文件,主要用于处理数据和布局页面

RootCell.h

 #import <UIKit/UIKit.h>

 @interface RootCell : UICollectionViewCell

 @property (nonatomic, strong) UIImageView *photoView;

 @end

RootCell.m

 #import "RootCell.h"

 @implementation RootCell

 - (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.photoView = [[UIImageView alloc] init];
[self.contentView addSubview:self.photoView];
}
return self;
} - (void)layoutSubviews { self.photoView.frame = self.bounds; } @end

RootCell就是每一个Item的样式, 也就是一张张图片

WaterFlowLayout.h

 #import <UIKit/UIKit.h>

 @protocol WaterFlowLayoutDelegate <NSObject>

 // 返回每一个item的高度
- (CGFloat)heightForItemAtIndexPath:(NSIndexPath *)indexPath; @end @interface WaterFlowLayout : UICollectionViewLayout // item的大小,需要根据这个获取宽度
@property (nonatomic, assign) CGSize itemSize; // 内边距的设置
@property (nonatomic, assign) UIEdgeInsets sectionInsets; // item的间距(这里水平方向和垂直方向的间距一样)
@property (nonatomic, assign) CGFloat spacing; // 列数
@property (nonatomic, assign) NSInteger numberOfColumn; // 设置代理,用于获取item的高度
@property (nonatomic, weak) id<WaterFlowLayoutDelegate>delegate; @end

WaterFlowLayout.m

 #import "WaterFlowLayout.h"

 @interface WaterFlowLayout ()

 // 声明私有属性
// 保存一共有多少个item
@property (nonatomic, assign) NSInteger numberOfItems; // 保存计算好的每一个item的信息
@property (nonatomic, strong) NSMutableArray *itemAttributes; // 保存每一列的高度
@property (nonatomic, strong) NSMutableArray *columnHeights; // 声明私有方法
// 找到当前最长列
- (NSInteger)indexOfHeightestColumn; // 找到当前最短列
- (NSInteger)indexOfShortestColumn; @end @implementation WaterFlowLayout // 懒加载
- (NSMutableArray *)itemAttributes {
if (!_itemAttributes) {
_itemAttributes = [NSMutableArray array];
}
return _itemAttributes;
} - (NSMutableArray *)columnHeights {
if (!_columnHeights) {
_columnHeights = [NSMutableArray array];
}
return _columnHeights;
} // 找到当前最长列
- (NSInteger)indexOfHeightestColumn {
// 记录最长列的下标
NSInteger index = ;
// 记录最长列的高度
CGFloat length = ;
for (int i = ; i < self.columnHeights.count; i++) {
// 将数组中的对象转为基本数值
CGFloat currentLength = [self.columnHeights[i] floatValue];
if (currentLength > length) {
length = currentLength;
index = i;
}
}
return index;
} // 找到当前最短列
- (NSInteger)indexOfShortestColumn {
NSInteger index = ;
CGFloat length = MAXFLOAT;
for (int i = ; i < self.columnHeights.count; i++) { CGFloat currentLength = [self.columnHeights[i] floatValue];
if (currentLength < length) {
length = currentLength;
index = i;
}
}
return index;
} // 接下来重写三个方法 // 准备布局,在这里计算每个item的frame
- (void)prepareLayout { // 拿到一共有多少个item
self.numberOfItems = [self.collectionView numberOfItemsInSection:];
// 每一列添加一个top高度
for (int i = ; i < self.numberOfColumn; i++) {
// @() NSNumber字面量创建对象
self.columnHeights[i] = @(self.sectionInsets.top);
} // 依次为每个item设置位置信息,并存储在数组中
for (int i = ; i < self.numberOfItems; i++) { // 1.找到最短列的下标
NSInteger shortestIndex = [self indexOfShortestColumn];
// 2.计算X 目标X = 内边距左间距 + (宽 + item间距)*最短列下标
CGFloat detalX = self.sectionInsets.left + shortestIndex * (self.itemSize.width + self.spacing);
// 3.找到最短列的高度
CGFloat height = [self.columnHeights[shortestIndex] floatValue];
// 4.计算Y
CGFloat detalY = height + self.spacing;
// 5.创建indexPath
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:]; // 6.调用代理方法计算高度
CGFloat itemHeight = ;
if (_delegate && [_delegate respondsToSelector:@selector(heightForItemAtIndexPath:)]) {
itemHeight = [_delegate heightForItemAtIndexPath:indexPath];
} // 定义保存位置信息的对象
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; // 7.生成frame
attributes.frame = CGRectMake(detalX, detalY, self.itemSize.width, itemHeight);
// 8.将位置信息添加到数组中
[self.itemAttributes addObject:attributes]; // 9.更新这一列的高度
self.columnHeights[shortestIndex] = @(detalY + itemHeight);
} } // 返回UICollectionView的大小
- (CGSize)collectionViewContentSize { // 求最高列的下标
NSInteger heightest = [self indexOfHeightestColumn];
// 最高列的高度
CGFloat height = [self.columnHeights[heightest] floatValue];
// 拿到collectionView的原始大小
CGSize size = self.collectionView.frame.size;
size.height = height + self.sectionInsets.bottom; return size;
} // 返回每一个item的位置信息
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.itemAttributes;
} @end

WaterFlowLayout 就是我们自定义的 瀑布流 的文件

DataModel.h

 #import <Foundation/Foundation.h>

 @interface DataModel : NSObject

 @property (nonatomic, copy) NSString *thumbURL;

 @property (nonatomic, assign) float width;

 @property (nonatomic, assign) float height;

 @end

DataModel.m

 #import "DataModel.h"

 @implementation DataModel

 // 防崩
- (void)setValue:(id)value forUndefinedKey:(NSString *)key { } @end