话不多说,先看效果:
这是我前几天在项目空档期,仿的小红书,它的主页就是典型的瀑布流。下面咱们就分析一下:
思路:
-
collectionViewCell
的大小是自适应的,即高度不固定。所以这个cell,我们需要自定义。我是xib搭的,简单高效。 -
collectionView
中cell的布局是错位的。所以我们要做的是在视图加载时,找出高度短的那一列,在它下面添加其它cell。
难点和关键点就是上面分析的这两个方面。下面咱们逐一解决:
首先,这个高度自适应的cell该怎么搭建呢?其实so easy。就是xib,设置控件约束的问题。那我们该怎么设置约束呢?这个cell的高度其实是因内部的imageView的高度变化的。所以,我们只讲imageView的约束设置。估计,我不说,大家也知道怎么做。就是,不设置imageView高度的约束。然后设置以下约束:宽度等于cell的宽度,距离cell左侧为0,顶部top为0,距离下方控件一定距离。这样就OK了。
接下来要讲的才是重中之重!
2.1 重写布局类(MCWaterFlowLayout),创建一个继承UICollectionViewFlowLayout
的布局类。
2.2 重写一些父类方法:
重写prepareLayout方法
作用:在这个方法做一些初始化操作。
重写layoutAttributesForElementsInRect方法
作用:返回当前屏幕视图框内item的属性,可以直接返回所有item属性,指定区域的cell布局对象.定新的区域的时候调用
重写collectionViewContentSize方法
作用:决定collectionView的可滚动范围直接上代码:
MCWaterFlowLayout.h
@interface MCWaterFlowLayout : UICollectionViewFlowLayout
@optional
-(NSInteger)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout columnCountForSection:(NSInteger)section;
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForHeaderInSection:(NSInteger)section;
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout heightForFooterInSection:(NSInteger)section;
@end
@protocol
@interface MCWaterFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) NSInteger columnCount; // default 2
@property (nonatomic, assign) CGFloat headerHeight; // default 0
@property (nonatomic, assign) CGFloat footerHeight; // default 0
// contentsize的高度
@property (nonatomic, assign) CGFloat contentHeight;
@end
MCWaterFlowLayout.m
@interface MCWaterFlowLayout()
@property (nonatomic, weak) id<MCWaterFlowLayoutDelegate> delegate;
// 存放所有item的attrubutes属性
@property (nonatomic, strong) NSMutableArray *itemAttributes;
// 存放所有段头或断尾的attrubutes属性
@property (nonatomic, strong) NSMutableArray *supplementaryAttributes;
@end
@implementation MCWaterFlowLayout
-(id)init
{
self = [super init];
if (self) {
[self setup];
}
return self;
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self setup];
}
return self;
}
//设置默认属性
-(void)setup
{
self.minimumInteritemSpacing = 10.0f;
self.minimumLineSpacing = 10.0f;
self.sectionInset = UIEdgeInsetsMake(0.0f, 10.0f, 10.0f, 10.0f);
_columnCount = 2;
_itemAttributes = [NSMutableArray array];
_supplementaryAttributes = [NSMutableArray array];
}/**
* 准备好布局时调用
*/
-(void)prepareLayout
{
self.contentHeight = 0;
[self.itemAttributes removeAllObjects];
[self.supplementaryAttributes removeAllObjects];
NSInteger numberOfSections = [self.collectionView numberOfSections];
for (NSInteger section = 0; section < numberOfSections; section++) {
CGFloat minimumInteritemSpacing = [self minimumInteritemSpacingForSection:section];
CGFloat minimumLineSpacing = [self minimumLineSpacingForSection:section];
UIEdgeInsets sectionInset = [self sectionInsetForSection:section];
NSInteger columnCount = [self columnCountForSection:section];
CGFloat headerHeight = [self headerHeightForSection:section];
CGFloat footerHeight = [self footerHeightForSection:section];
NSMutableDictionary *supplementary = [[NSMutableDictionary alloc] initWithCapacity:2];
self.contentHeight += sectionInset.top;
//header 设置段头视图的frame
if (headerHeight > 0) {
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
attributes.frame = CGRectMake(0, self.contentHeight, self.collectionView.frame.size.width, headerHeight);
[self.itemAttributes addObject:attributes];
[supplementary setObject:attributes forKey:UICollectionElementKindSectionHeader];
self.contentHeight = CGRectGetMaxY(attributes.frame);
}
//cellitem 设置cell视图的frame
NSInteger itemCount = [self.collectionView numberOfItemsInSection:section];
NSMutableArray *columnHeights = [[NSMutableArray alloc] initWithCapacity:columnCount];
for (NSInteger i = 0; i < columnCount; i++) {
columnHeights[i] = @(self.contentHeight);
}
for (NSInteger i = 0; i < itemCount; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:section];
//返回数组最小值对应的索引值,即找出位置高度最短的一列
NSInteger columnIndex = [columnHeights indexOfObject:[columnHeights valueForKeyPath:@"@min.self"]];
CGSize size = [self itemSizeForIndexPath:indexPath];
CGFloat x = sectionInset.left + (size.width + minimumInteritemSpacing) * columnIndex;
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
if (indexPath.row == 0) {
attributes.frame = CGRectMake(x, [columnHeights[columnIndex] floatValue], size.width, size.height);
}
attributes.frame = CGRectMake(x, [columnHeights[columnIndex] floatValue], size.width, size.height);
[self.itemAttributes addObject:attributes];
columnHeights[columnIndex] = @(CGRectGetMaxY(attributes.frame) + minimumLineSpacing);
}
self.contentHeight = [[columnHeights valueForKeyPath:@"@max.self"] floatValue];
if (itemCount == 0) {
self.contentHeight += [UIScreen mainScreen].bounds.size.height;
}
//footer 设置段尾视图的frame
if (footerHeight > 0) {
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter withIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
attributes.frame = CGRectMake(0, self.contentHeight, self.collectionView.frame.size.width, footerHeight);
[self.itemAttributes addObject:attributes];
[supplementary setObject:attributes forKey:UICollectionElementKindSectionFooter];
self.contentHeight = CGRectGetMaxY(attributes.frame);
}
[self.supplementaryAttributes addObject:supplementary];
self.contentHeight += sectionInset.bottom;
}
}
-(CGSize)collectionViewContentSize
{
CGSize size = CGSizeMake(self.collectionView.frame.size.width, self.contentHeight);
return size;
}
/**
* 返回当前屏幕视图框内item的属性,可以直接返回所有item属性,指定区域的cell布局对象.定新的区域的时候调用
*/
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
//判断矩形结构是否交叉,两个矩形对象是否重叠
NSArray *array = [self.itemAttributes filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(UICollectionViewLayoutAttributes *evaluatedObject, NSDictionary *bindings) {
// NSLog(@"%@*********%@",NSStringFromCGRect(rect),NSStringFromCGRect(evaluatedObject.frame));
return CGRectIntersectsRect(rect, evaluatedObject.frame);
}]];
return array;
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger index = indexPath.item;
for (NSInteger section = 0; section < indexPath.section; section++) {
index += [self.collectionView numberOfItemsInSection:section];
}
return self.itemAttributes[index];
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
return self.supplementaryAttributes[indexPath.section][kind];
}
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
CGRect oldBounds = self.collectionView.bounds;
if (CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds)) {
return YES;
}
return NO;
}
#pragma mark -
-(id<MCWaterFlowLayoutDelegate>)delegate
{
if (_delegate == nil) {
_delegate = (id<MCWaterFlowLayoutDelegate>)self.collectionView.delegate;
}
return _delegate;
}
-(NSInteger)columnCountForSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(collectionView:layout:columnCountForSection:)]) {
self.columnCount = [self.delegate collectionView:self.collectionView layout:self columnCountForSection:section];
}
return self.columnCount;
}
/**
* 获取段头的高度
*/
-(CGFloat)headerHeightForSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(collectionView:layout:heightForHeaderInSection:)]) {
self.headerHeight = [self.delegate collectionView:self.collectionView layout:self heightForHeaderInSection:section];
}
return self.headerHeight;
}
/**
* 获取段尾的高度
*/
-(CGFloat)footerHeightForSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(collectionView:layout:heightForFooterInSection:)]) {
self.footerHeight = [self.delegate collectionView:self.collectionView layout:self heightForFooterInSection:section];
}
return self.footerHeight;
}
-(UIEdgeInsets)sectionInsetForSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(collectionView:layout:insetForSectionAtIndex:)]) {
self.sectionInset = [self.delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:section];
}
return self.sectionInset;
}
-(CGFloat)minimumInteritemSpacingForSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(collectionView:layout:minimumInteritemSpacingForSectionAtIndex:)]) {
self.minimumInteritemSpacing = [self.delegate collectionView:self.collectionView layout:self minimumInteritemSpacingForSectionAtIndex:section];
}
return self.minimumInteritemSpacing;
}
-(CGFloat)minimumLineSpacingForSection:(NSInteger)section
{
if ([self.delegate respondsToSelector:@selector(collectionView:layout:minimumLineSpacingForSectionAtIndex:)]) {
self.minimumLineSpacing = [self.delegate collectionView:self.collectionView layout:self minimumLineSpacingForSectionAtIndex:section];
}
return self.minimumLineSpacing;
}
/**
* 获取每个cell的size
*/
-(CGSize)itemSizeForIndexPath:(NSIndexPath *)indexPath
{
CGFloat itemWidth = ([UIScreen mainScreen].bounds.size.width-self.sectionInset.left-self.sectionInset.right-(self.columnCount-1)*self.minimumInteritemSpacing)/self.columnCount;
self.itemSize = CGSizeMake(itemWidth, itemWidth);
if ([self.delegate respondsToSelector:@selector(collectionView:layout:sizeForItemAtIndexPath:)]) {
CGSize size = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
self.itemSize = CGSizeMake(self.itemSize.width, floorf(size.height * self.itemSize.width / size.width));
}
return self.itemSize;
}
@end
- 那咱们该怎么用呢?很简单,在collectionView的初始化的时候绑定该布局类,并实现
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
方法以返回cell的高度。一般把cell的高度放入数组中。
如果有透视图的话,要实现- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
这个方法。
至此,就完成了!!!如果大家遇到什么问题,尽管提,相互交流。