CustomLayout.h
#import <UIKit/UIKit.h>
@protocol CustomLayoutDelegate <NSObject>
- (CGFloat)collectionViewLayout:(UICollectionViewLayout*)layout andIndexPath:(NSIndexPath*)indexPath;
@end
@interface CustomLayout : UICollectionViewLayout
@property (nonatomic,assign)CGFloat itemWidth;
@property (nonatomic,assign)CGFloat itemSpace;
@property (nonatomic,weak)id<CustomLayoutDelegate>delegate;
@end
CustomLayout.m
#import "CustomLayout.h"
@interface CustomLayout ()
{
NSMutableArray *_attrs;
NSMutableArray *_infos;
}
@end
@implementation CustomLayout
- (instancetype)init{
self = [super init];
if (self) {
_attrs = [NSMutableArray array];
//给每一列第一个的上一个的y;
_infos = @[@0,@0,@0].mutableCopy;
}
return self;
}
//给attributes数组赋值
- (void)prepareLayout{
[super prepareLayout];
//有多个Section
NSInteger sections = [self.collectionView numberOfSections];
for (NSInteger se = 0; se<sections; se++) {
NSInteger itC = [self.collectionView numberOfItemsInSection:se];
for (NSInteger j = 0; j<itC; j++) {
}
}
//只有一个Sections
NSInteger itemCounts = [self.collectionView numberOfItemsInSection:0];
//算出列数
NSInteger columCount = (self.collectionView.bounds.size.width - self.itemSpace)/(self.itemSpace + self.itemWidth);
//算出每个item之间的间距
self.itemSpace = (self.collectionView.bounds.size.width - columCount * self.itemWidth)/(columCount + 1);
for (NSInteger i = 0; i<itemCounts; i++) {
//算出item处于哪一列
NSInteger columIndex = i % columCount;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
//根据下标找到item的高度
CGFloat itemHeight = [self.delegate collectionViewLayout:self andIndexPath:indexPath];
//创建attributes数组
UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
//计算出x坐标
CGFloat p_x = (columIndex + 1)*self.itemSpace + columIndex*self.itemWidth;
//根据数组拿出上一个点高的y
NSNumber *lastP = _infos[columIndex];
CGFloat lastPValue = lastP.floatValue;
//计算出y坐标
CGFloat p_y = lastPValue + self.itemSpace;
#if 0
if(i == 10){
attr.frame = CGRectMake(p_x, p_y, self.itemWidth+100, itemHeight);
}else{
attr.frame = CGRectMake(p_x, p_y, self.itemWidth, itemHeight);
}
#endif
attr.frame = CGRectMake(p_x, p_y, self.itemWidth, itemHeight);
//将自己高的y放到数组中去
_infos[columIndex] = @(p_y+itemHeight);
//放入数组
[_attrs addObject:attr];
}
}
//返回数组attributes
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
//返回数组
return _attrs;
}
//使collectionView可以滑动
- (CGSize)collectionViewContentSize{
//找出数组中的最大值
NSArray *tempArray = [_infos sortedArrayUsingSelector:@selector(compare:)];
//上面函数所返回的数组是升序的
NSNumber *maxNum = tempArray.lastObject;
//返回整个collectionView的宽高
return CGSizeMake(self.collectionView.bounds.size.width, maxNum.floatValue);
}
@end