苹果在TableView之后推出的CollectionView,这两种自定义视图满足了绝大部分项目的需求,在初识iOS的时候,一直在纠结这两种视图应该用哪种,随着代码量的提升和对布局的认识,总结出CollectionView适合需要繁琐布局的视图,TableView比较适合垂直而下,数据源比较相似的视图。
CollectionView强大的自定义布局则基于UICollectionViewLayout这个类,实现瀑布流的基本步骤应该是:设定好列数和行、列间距 →→ 从数据源依次取出item填入CollectionView(此时应该通过delegate或block获取到image的size),记录其UICollectionViewLayoutAttributes属性并记录所在列的最大y值 →→ 返回item的Attributes数组 →→ 计算CollectionView的ContentSize。
具体代码如下:
新建一个类继承于UICollectionViewLayout。
#import <UIKit/UIKit.h>
@class JTWaterFallLayout;
@protocol JTWaterFallLayoutDelegate <NSObject>
@required
// 计算item高度的代理方法,将item的高度与indexPath传递给外界
- (CGFloat)waterfallLayout:(JTWaterFallLayout *)waterfallLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath;
@end
@interface JTWaterFallLayout : UICollectionViewLayout
// 总列数,默认2
@property (nonatomic, assign) NSInteger columnCount;
// 列间距,默认0
@property (nonatomic, assign) NSInteger columnSpacing;
// 行间距,默认0
@property (nonatomic, assign) NSInteger rowSpacing;
// section与collectionView的间距,默认(0,0,0,0)
@property (nonatomic, assign) UIEdgeInsets sectionInset;
// 一次性设置列间距,行间距,sectionInset三个属性
- (void)setColumnSpacing:(NSInteger)columnSpacing rowSpacing:(NSInteger)rowSepacing sectionInset:(UIEdgeInsets)sectionInset;
/**
以下代理属性与block属性二选一,用来设置每一个item的高度
会将item的宽度与indexPath传递给外界
如果两个都设置,block的优先级高,即代理无效
*/
// 代理,用来计算item的高度
@property (nonatomic, weak) id<JTWaterFallLayoutDelegate> delegate;
// 计算item高度的block,将item的高度与indexPath传递给外界
@property (nonatomic, strong) CGFloat(^itemHeightBlock)(CGFloat itemHeight,NSIndexPath *indexPath);
// 两个初始化方法任选其一
+ (instancetype)waterFallLayoutWithColumnCount:(NSInteger)columnCount;
- (instancetype)initWithColumnCount:(NSInteger)columnCount;
@end
复制代码
#import "JTWaterFallLayout.h"
@interface JTWaterFallLayout ()
// 用来记录每一列的最大y值
@property (nonatomic, strong) NSMutableDictionary *maxYDic;
// 保存每一个item的attributes
@property (nonatomic, strong) NSMutableArray *attributesArray;
@end
@implementation JTWaterFallLayout
#pragma mark - init
- (instancetype)init
{
if (self = [super init])
{
self.columnCount = 2;
}
return self;
}
- (instancetype)initWithColumnCount:(NSInteger)columnCount
{
if (self = [super init]) {
self.columnCount = columnCount;
}
return self;
}
+ (instancetype)waterFallLayoutWithColumnCount:(NSInteger)columnCount
{
return [[self alloc] initWithColumnCount:columnCount];
}
#pragma mark - method
- (void)setColumnSpacing:(NSInteger)columnSpacing rowSpacing:(NSInteger)rowSepacing sectionInset:(UIEdgeInsets)sectionInset
{
self.columnSpacing = columnSpacing;
self.rowSpacing = rowSepacing;
self.sectionInset = sectionInset;
}
#pragma mark - 布局相关方法
// 布局前的准备工作,CollectionView第一次布局和布局失效时都会调用
- (void)prepareLayout
{
[super prepareLayout];
//初始化字典,有几列就有几个键值对,key为列,value为列的最大y值,初始值为上内边距
for (int i = 0; i < self.columnCount; i++) {
self.maxYDic[@(i)] = @(self.sectionInset.top);
}
//根据collectionView获取总共有多少个item
NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];
[self.attributesArray removeAllObjects];
//为每一个item创建一个attributes并存入数组
for (int i = 0; i < itemCount; i++) {
UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
[self.attributesArray addObject:attributes];
}
}
// 返回indexPath位置上的item的布局属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
//根据indexPath获取item的attributes
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
//item的宽度 = (collectionView的宽度 - 内边距与列间距) / 列数
CGFloat itemWidth = (self.collectionView.bounds.size.width - self.sectionInset.left - self.sectionInset.right - (self.columnCount - 1) * self.columnSpacing) / self.columnCount;
CGFloat itemHeight = 0;
//获取item的高度,由外界计算得到
if (self.itemHeightBlock) {
itemHeight = self.itemHeightBlock(itemWidth, indexPath);
} else {
if ([self.delegate respondsToSelector:@selector(waterfallLayout:itemHeightForWidth:atIndexPath:)])
itemHeight = [self.delegate waterfallLayout:self itemHeightForWidth:itemWidth atIndexPath:indexPath];
}
//找出最短的那一列
__block NSNumber *minIndex = @0;
[self.maxYDic enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, NSNumber *obj, BOOL *stop) {
if ([self.maxYDic[minIndex] floatValue] > obj.floatValue) {
minIndex = key;
}
}];
//根据最短列的列数计算item的x值
CGFloat itemX = self.sectionInset.left + (self.columnSpacing + itemWidth) * minIndex.integerValue;
//item的y值 = 最短列的最大y值 + 行间距
CGFloat itemY = [self.maxYDic[minIndex] floatValue] + self.rowSpacing;
//设置attributes的frame
attributes.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);
//更新字典中的最大y值
self.maxYDic[minIndex] = @(CGRectGetMaxY(attributes.frame));
return attributes;
}
// 计算collectionView的contentSize
- (CGSize)collectionViewContentSize
{
__block NSNumber *maxIndex = @0;
//遍历字典,找出最长的那一列
[self.maxYDic enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, NSNumber *obj, BOOL *stop) {
if ([self.maxYDic[maxIndex] floatValue] < obj.floatValue) {
maxIndex = key;
}
}];
//collectionView的contentSize.height就等于最长列的最大y值+下内边距
return CGSizeMake(0, [self.maxYDic[maxIndex] floatValue] + self.sectionInset.bottom);
}
// 返回rect范围内item的attributes布局属性的数组
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
return self.attributesArray;
}
#pragma mark - lazy init
- (NSMutableDictionary *)maxYDic
{
if (!_maxYDic) {
_maxYDic = [[NSMutableDictionary alloc] init];
}
return _maxYDic;
}
- (NSMutableArray *)attributesArray
{
if (!_attributesArray) {
_attributesArray = [NSMutableArray array];
}
return _attributesArray;
}
@end
复制代码
如何使用:
// 首先进行初始化
JTWaterFallLayout *waterfallFlowLayout = [JTWaterFallLayout waterFallLayoutWithColumnCount:2];
[waterfallFlowLayout setColumnSpacing:5 rowSpacing:5 sectionInset:UIEdgeInsetsMake(0, 5, 5, 5)];
waterfallFlowLayout.delegate = self; // 记得设置代理
// ① 如果是代码写的CollectionView
self.collectionViewByCode = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 200, 200) collectionViewLayout:waterfallFlowLayout];
// ② 如果是xib里写的CollectionView
self.collectionViewByXib.collectionViewLayout = waterfallFlowLayout;
// 再实现相应代理即可(也可以用block)
复制代码
还需要实现相关代理,注意Model中最好有Width和Height或图片比例,没有的话只能先用SDWebImage下载好图片,再传入代理,当然这样会特别的慢,影响用户体验。
- (CGFloat)waterfallLayout:(JTWaterfallLayout *)waterfallLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath
{
JTModel *model = [self.JTModelList objectAtIndex:indexPath.item];
if (model.height && model.width) {
self.itemWidth = itemWidth;
return model.height * 1.0 / model.width * itemWidth;
}
// 如果没有Width和Height属性,先预估100,待图片下载完之后计算出来再刷新CollectionView
return 100;
}
复制代码