瀑布流
效果图
1.新建一个继承UICollectionViewLayout的子类
2.定义属性
static const NSInteger count = 3;
static const CGFloat rowmagin = 10;
static const CGFloat columnmagin = 10;
static const UIEdgeInsets edge = {10,10,10,10};
/** 存放每个item的属性数组 */
@property (nonatomic,strong) NSMutableArray *array;
/** 存放最短高度的数组 */
@property (nonatomic,strong) NSMutableArray *minheight;
/** 内容的高度 */
@property (nonatomic,assign) CGFloat contentH;
3.实现prepareLayout方法(准备布局)
- (void)prepareLayout {
[super prepareLayout];
[self.minheight removeAllObjects];
for (NSInteger i = 0; i < count; i++) {
[self.minheight addObject:@(edge.top)];
}
[self.array removeAllObjects];
NSInteger count = [self.collectionView numberOfItemsInSection:0];
for (int i=0; i<count; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
UICollectionViewLayoutAttributes *attr = [self layoutAttributesForItemAtIndexPath:indexPath];
[self.array addObject:attr];
}
}
4.实现layoutAttributesForItemAtIndexPath方法创建item属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewLayoutAttributes *attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGFloat collectViewW = self.collectionView.frame.size.width;
CGFloat w = (collectViewW - edge.left - edge.right - columnmagin * (count - 1)) / count;
CGFloat h = arc4random()%200 + 50;
NSInteger minColumn = 0;
CGFloat minColumnHeight = [self.minheight[0] doubleValue];
for (NSInteger i=1; i<count; i++) {
CGFloat columnHeight = [self.minheight[i] doubleValue];
if (minColumnHeight > columnHeight) {
minColumnHeight = columnHeight;
minColumn = i;
}
}
CGFloat x = edge.left + minColumn * (w + columnmagin);
CGFloat y = minColumnHeight;
if (y != edge.top) {
y += rowmagin;
}
attr.frame = CGRectMake(x, y, w, h);
self.minheight[minColumn] = @(CGRectGetMaxY(attr.frame));
CGFloat contentH = [self.minheight[minColumn] doubleValue];
if (self.contentH < contentH) {
self.contentH = contentH;
}
return attr;
}
5.实现layoutAttributesForElementsInRect方法,返回所有item的属性(也就是刚刚保存属性的那个数组)
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return self.array;
}
6.实现collectionViewContentSize方法设置内容高度
- (CGSize)collectionViewContentSize {
return CGSizeMake(0 , self.contentH + edge.bottom);
}
7.想要动态改变item的高度,创建代理协议
@class WaterLayou;
@protocol WaterDelegate <NSObject>
- (CGFloat)waterFlowLayout:(WaterLayou *)waterFlowLayout heightForItemAtIndex:(NSUInteger)index itemWidth:(CGFloat)itemWidth;
@end
@interface WaterLayou : UICollectionViewLayout
@property (nonatomic,weak) id <WaterDelegate>waterdelegate;
@end
CGFloat h = [self.delegate waterFlowLayout:self heightForItemAtIndex:indexPath.item itemWidth:w];
仅供参考,错误勿怪!