話不多說,先看效果:
這是我前幾天在項目空檔期季俩,仿的小紅書钮糖,它的主頁就是典型的瀑布流。下面咱們就分析一下:
思路:
-
collectionViewCell
的大小是自適應(yīng)的,即高度不固定店归。所以這個cell阎抒,我們需要自定義。我是xib搭的消痛,簡單高效且叁。 -
collectionView
中cell的布局是錯位的。所以我們要做的是在視圖加載時秩伞,找出高度短的那一列逞带,在它下面添加其它cell。
難點和關(guān)鍵點就是上面分析的這兩個方面纱新。下面咱們逐一解決:
首先展氓,這個高度自適應(yīng)的cell該怎么搭建呢?其實so easy怒炸。就是xib带饱,設(shè)置控件約束的問題。那我們該怎么設(shè)置約束呢阅羹?這個cell的高度其實是因內(nèi)部的imageView的高度變化的。所以教寂,我們只講imageView的約束設(shè)置捏鱼。估計,我不說酪耕,大家也知道怎么做导梆。就是,不設(shè)置imageView高度的約束迂烁。然后設(shè)置以下約束:寬度等于cell的寬度看尼,距離cell左側(cè)為0,頂部top為0盟步,距離下方控件一定距離藏斩。這樣就OK了。
接下來要講的才是重中之重却盘!
2.1 重寫布局類(MCWaterFlowLayout)狰域,創(chuàng)建一個繼承UICollectionViewFlowLayout
的布局類。
2.2 重寫一些父類方法:
重寫prepareLayout方法
作用:在這個方法做一些初始化操作黄橘。
重寫layoutAttributesForElementsInRect方法
作用:返回當前屏幕視圖框內(nèi)item的屬性兆览,可以直接返回所有item屬性,指定區(qū)域的cell布局對象.定新的區(qū)域的時候調(diào)用
重寫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;
}
//設(shè)置默認屬性
-(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];
}/**
* 準備好布局時調(diào)用
*/
-(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 設(shè)置段頭視圖的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 設(shè)置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];
//返回數(shù)組最小值對應(yīng)的索引值,即找出位置高度最短的一列
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 設(shè)置段尾視圖的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;
}
/**
* 返回當前屏幕視圖框內(nèi)item的屬性塞关,可以直接返回所有item屬性,指定區(qū)域的cell布局對象.定新的區(qū)域的時候調(diào)用
*/
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
//判斷矩形結(jié)構(gòu)是否交叉抬探,兩個矩形對象是否重疊
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的初始化的時候綁定該布局類小压,并實現(xiàn)
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
方法以返回cell的高度线梗。一般把cell的高度放入數(shù)組中。
如果有透視圖的話场航,要實現(xiàn)- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
這個方法缠导。
至此,就完成了8攘 Fг臁!如果大家遇到什么問題孩饼,盡管提髓削,相互交流。