collectionView瀑布流的設計與實現

話不多說,先看效果:

collectionView瀑布流.gif

這是我前幾天在項目空檔期,仿的小紅書,它的主頁就是典型的瀑布流。下面咱們就分析一下:

思路:

  • collectionViewCell的大小是自適應的,即高度不固定。所以這個cell,我們需要自定義。我是xib搭的,簡單高效。
  • collectionView中cell的布局是錯位的。所以我們要做的是在視圖加載時,找出高度短的那一列,在它下面添加其它cell。

難點和關鍵點就是上面分析的這兩個方面。下面咱們逐一解決:

  1. 首先,這個高度自適應的cell該怎么搭建呢?其實so easy。就是xib,設置控件約束的問題。那我們該怎么設置約束呢?這個cell的高度其實是因內部的imageView的高度變化的。所以,我們只講imageView的約束設置。估計,我不說,大家也知道怎么做。就是,不設置imageView高度的約束。然后設置以下約束:寬度等于cell的寬度,距離cell左側為0,頂部top為0,距離下方控件一定距離。這樣就OK了。

  2. 接下來要講的才是重中之重!
    2.1 重寫布局類(MCWaterFlowLayout),創建一個繼承UICollectionViewFlowLayout的布局類。
    2.2 重寫一些父類方法:
    重寫prepareLayout方法
    作用:在這個方法做一些初始化操作。
    重寫layoutAttributesForElementsInRect方法
    作用:返回當前屏幕視圖框內item的屬性,可以直接返回所有item屬性,指定區域的cell布局對象.定新的區域的時候調用
    重寫collectionViewContentSize方法
    作用:決定collectionView的可滾動范圍

  3. 直接上代碼:
    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
  1. 那咱們該怎么用呢?很簡單,在collectionView的初始化的時候綁定該布局類,并實現- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath方法以返回cell的高度。一般把cell的高度放入數組中。
    如果有透視圖的話,要實現- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath這個方法。

至此,就完成了!!!如果大家遇到什么問題,盡管提,相互交流。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容