1. 程式人生 > >iOS 自定義UICollectionViewLayout實現瀑布流

iOS 自定義UICollectionViewLayout實現瀑布流

前言

hihi,勇敢的小夥伴兒們大家好,很高興今天又能更新了,首先照例說一下學習這個瀑布流的人生感悟(一本正經)。

在2015年的時候我已經瞭解瀑布流這個概念了,也知道可以用UICollectionView來實現,但是有意思的是我從業幾年來,從未在專案中真正實踐過,所以我就一!直!沒!學!

但!是!


在若干年後的今天,我們專案中要使用瀑布流的佈局。

嗯,這時候知道知識的重要性了,技多不壓身,多學一點是一點兒,早晚用得到!

首先先掛上我的Demo地址:瀑布流

話不多說,開始我們今天的學習。

正文

為了讓新手朋友(emmm,其實我也算是新手)由淺入深的學習瀑布流的實現。不需要可以直接跳過此段內容。

首先我們需要了解一下UICollectionView。

UICollectionView簡介

關於UICollectionView,官方解釋是:管理資料項的有序集合,並使用可定製的佈局呈現它們。

在iOS中最簡單的UICollectionView就是GridView(網格檢視),可以以多列的方式將資料進行展示。

標準的UICollectionView包含以下3個部分,它們都是UIView的子類:

❶Cell:用於展示內容的主體,可以定製其尺寸和內容。

❷Supplementary View:用於追加檢視,和UITableView裡面的Header和Footer的作用類似。

❸Decoration View:用於裝飾檢視,是每個Section的背景。

(emmmm...我好像不太知道...才疏學淺才疏學淺...)


UICollectionView和UITableView對比

相同點

❶都是繼承自UIScrollView,支援滾動。

❷都支援資料單元格的重用機制。

❸都是通過代理方法和資料來源方法來實現控制和顯示。

不同點

❶UICollectionView的section裡面的資料單元叫做item,UITableView的叫做cell

❷UICollectionView的佈局使用UICollectionViewLayout或者其子類UICollectionViewFlawLayout容易實現自定義佈局。

實現一個簡單的UICollectionView的步驟:

由於UICollectionView和UITableView類似,所以實現一個UICollectionView的步驟也和UITableView相同,最大的區別在於UICollectionView的佈局。

1.建立佈局

❶使用UICollectionViewFlowLayout或者UICollectionViewLayout實現佈局。

❷佈局裡面實現每個通過itemSize屬性設定item的尺寸。

❸用scrollDirection屬性設定item的滾動方向,垂直或者橫向。

typedef NS_ENUM(NSInteger, UICollectionViewScrollDirection) {
    UICollectionViewScrollDirectionVertical,
    UICollectionViewScrollDirectionHorizontal
};

❹其他自定義佈局

2.建立UICollectionView

❶用-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout方法進行初始化

UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 100, collectionViewW, collectionViewH) collectionViewLayout:layout];

❷設定UICollectionView的代理為控制器

3.實現代理協議

@protocol UICollectionViewDataSource <NSObject>
@required
/**
* 返回每個section裡面的item的數量
*/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;

/**
* 返回每個item的具體樣式
*/
- ( UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;

@optional
/**
* 返回有多少個section
*/
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView;

/**
* 返回UICollectionReusableView
*/
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

/**
* 設定某個Item是否可以移動
*/
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath ;

/**
*移動item的使用呼叫的方法
*/
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath ;

- (nullable NSArray<NSString *> *)indexTitlesForCollectionView:(UICollectionView *)collectionView ;

- (NSIndexPath *)collectionView:(UICollectionView *)collectionView indexPathForIndexTitle:(NSString *)title atIndex:(NSInteger)index ;

@end

示例程式碼

#import "ViewController.h"

static NSString * const cellID = @"cellID";

@interface ViewController ()<UICollectionViewDataSource>

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 建立佈局
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(50, 50);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

    // 建立collectionView
    CGFloat collectionViewW = self.view.frame.size.width;
    CGFloat collectionViewH = 200;
    UICollectionView * collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 100, collectionViewW, collectionViewH) collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor blackColor];
    collectionView.dataSource = self;
    [self.view addSubview:collectionView];
    
    // 註冊
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellID];
}


#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 50;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    // 設定圓角
    cell.layer.cornerRadius = 5.0;
    cell.layer.masksToBounds = YES;
    cell.backgroundColor = [UIColor redColor];
    

    return cell;
}

@end

實現效果


UICollectionViewDelegate

同樣的UICollectionView也有代理方法,在實現代理協議之後通過代理方法來實現和使用者的互動操作。具體來說主要負責一下三份工作:

cell的高亮效果顯示

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath;

cell的選中狀態

- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath; // called when the user taps on an already-selected item in multi-select mode
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath;

支援長按後的選單

- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender;
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender;

UICollectionViewLayout和UICollectionViewFlowLayout

UICollectionView的精髓就是UICollectionViewLayout,這也是UICollectionView和UITableView最大的不同。UICollectionViewLayout決定了UICollectionView是如何顯示在介面上的。在展示之間,一般需要生成合適的UICollectionViewLayout的子類物件,並將其賦值到UICollectionView的佈局屬性上。
UICollectionViewFlowLayout是UICollectionViewLayout的子類。這個佈局是最簡單最常用的。它實現了直線對其的佈局排布方式,Gird View就是用UICollectionViewFlowLayout佈局方式。

UICollectionViewLayout佈局的具體思路:

❶設定itemSize屬性,它定義了每一個item的大小。在一個示例中通過設定layout的itemSize屬性全域性的設定了cell的尺寸。如果想要對某個cell定製尺寸,可以使用-(CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath方法實現。

❷設定間隔,間隔可以指定item之間的間隔和每一行之間的間隔,間隔和itemSize一樣,既有全域性屬性,也可以對每一個item設定:

@property (nonatomic) CGFloat minimumLineSpacing;
@property (nonatomic) CGFloat minimumInteritemSpacing;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

❸設定滾動方向

typedef NS_ENUM(NSInteger, UICollectionViewScrollDirection) {
    UICollectionViewScrollDirectionVertical,
   UICollectionViewScrollDirectionHorizontal
};

❹設定Header和Footer的尺寸

設定Header和Footer的尺寸也分為全域性和區域性。在這裡需要注意滾動的方向,滾動的方向不同,header和footer的寬度和高度只有一個會起作用。垂直滾動時section間寬度為尺寸的高。

@property (nonatomic) CGSize headerReferenceSize;
@property (nonatomic) CGSize footerReferenceSize;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;

❺設定內邊距

@property (nonatomic) UIEdgeInsets sectionInset;
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex

瞭解了基本知識,開始用UICollectionView實現瀑布流

淘寶的猜你喜歡是很常見瀑布流用法了~(鬼知道為什麼我的淘寶突然有一天充斥了各種外貿,就因為我上知乎上看到了一篇行業內你知道哪些省錢的方法嗎???)


實現瀑布流的方式有幾種,但是比較簡單的是通過UICollectionView,因為collectionView自己會實現Cell的迴圈利用,所以自己不用實現迴圈利用的機制,瀑布流最重要的就是佈局,要選取最短的那一列來排布,保證每一列之間的間距不會太大。

實現步驟

❶ 呼叫- (void)prepareLayout; 進行初始化

❷ 重寫- (CGSize)collectionViewContentSize; 返回內容的大小

❸ 重寫- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;方法返回rect中所有元素的佈局屬性,返回的是一個數組

❹ 重寫- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;方法返回對應的indexPath的位置的cell的佈局屬性

❺ 重寫- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath;方法返回對應indexPath的位置的追加檢視的佈局屬性,如果沒有就不用過載

❻ 重寫- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString*)elementKind atIndexPath:(NSIndexPath *)indexPath;方法返回對應indexPath的位置的裝飾檢視的佈局屬性,如果沒有也不需要過載

❼ 重寫- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;當邊界發生變化時,是否應該重新整理

自定義UICollectionViewLayout佈局的示例程式碼

原部落格裡有描述上的錯誤以及程式碼裡有邏輯性錯誤,以下內容對此有適當的修改。

注意:我這裡因為我需要的佈局是item第二個是1:1比例的,其他格式按照1:1.5所以在- (CGFloat)waterFallLayout:(EWWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth;中做了修改,大家活學活用即可!!!

EWWaterFallLayout.h

//
//  EWWaterFallLayout.h
//  EWWaterFallLayout
//
//  Created by Emy on 2018/7/6.
//  Copyright © 2018年 Emy. All rights reserved.
//

#import <UIKit/UIKit.h>

@class EWWaterFallLayout;

@protocol EWWaterFallLayoutDataSource<NSObject>

@required
/**
  * 每個item的高度
  */
- (CGFloat)waterFallLayout:(EWWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth;

@optional
/**
 * 有多少列
 */
- (NSUInteger)columnCountInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;

/**
 * 每列之間的間距
 */
- (CGFloat)columnMarginInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;

/**
 * 每行之間的間距
 */
- (CGFloat)rowMarginInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;

/**
 * 每個item的內邊距
 */
- (UIEdgeInsets)edgeInsetsInWaterFallLayout:(EWWaterFallLayout *)waterFallLayout;

@end
                    
@interface EWWaterFallLayout : UICollectionViewLayout

/**
 * 代理
 */
@property (nonatomic, weak) id<EWWaterFallLayoutDataSource> delegate;

@end

EWWaterFallLayout.m

//
//  EWWaterFallLayout.m
//  EWWaterFallLayout
//
//  Created by Emy on 2018/7/6.
//  Copyright © 2018年 Emy. All rights reserved.
//

#import "EWWaterFallLayout.h"

/** 預設的列數 */
static const CGFloat EWDefaultColumnCount = 3;
/** 每一列之間的間距 */
static const CGFloat EWDefaultColumnMargin = 10;
/** 每一行之間的間距 **/
static const CGFloat EWDefaultFRowMargin = 10;
/** 內邊距 */
static const UIEdgeInsets EWDefaultEdgeInsets = {10,10,10,10};

@interface EWWaterFallLayout()
/** 存放所有的佈局屬性 */
@property (nonatomic, strong) NSMutableArray *attrsArr;
/** 存放所有列的當前高度 */
@property (nonatomic, strong) NSMutableArray *columnHeights;
/** 內容的高度 */
@property (nonatomic, assign) CGFloat contentHeight;

- (NSUInteger)columnCount;
- (CGFloat)columnMargin;
- (CGFloat)rowMargin;
- (UIEdgeInsets)edgeInsets;

@end

@implementation EWWaterFallLayout

#pragma mark 懶載入
- (NSMutableArray *)attrsArr {
    if (!_attrsArr) {
        _attrsArr = [NSMutableArray array];
    }
    return _attrsArr;
}

- (NSMutableArray *)columnHeights {
    if (!_columnHeights) {
        _columnHeights = [NSMutableArray array];
    }
    return _columnHeights;
}

#pragma mark 資料處理
/**
  * 列數
 */
- (NSUInteger)columnCount {
    if ([self.delegate respondsToSelector:@selector(columnCountInWaterFallLayout:)]) {
        return [self.delegate columnCountInWaterFallLayout:self];
    } else {
        return EWDefaultColumnCount;
    }
}

/**
 * 列間距
 */
- (CGFloat)columnMargin {
    if ([self.delegate respondsToSelector:@selector(columnMarginInWaterFallLayout:)]) {
        return [self.delegate columnMarginInWaterFallLayout:self];
    } else {
        return EWDefaultColumnMargin;
    }
}

/**
 * 行間距
 */
- (CGFloat)rowMargin {
    if ([self.delegate respondsToSelector:@selector(rowMarginInWaterFallLayout:)]) {
        return [self.delegate rowMarginInWaterFallLayout:self];
    } else {
        return EWDefaultFRowMargin;
    }
}

/**
 * item的內邊距
 */
- (UIEdgeInsets)edgeInsets {
    if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterFallLayout:)]) {
        return [self.delegate edgeInsetsInWaterFallLayout:self];
    } else {
        return EWDefaultEdgeInsets;
    }
}

/**
 * 初始化
 */
- (void)prepareLayout {
    [super prepareLayout];
    
    self.contentHeight = 0;
    
    //清除之前計算的所有高度
    [self.columnHeights removeAllObjects];
    
    //設定每一列預設的高度
    for (NSInteger i = 0; i < self.columnCount; i++) {
        [self.columnHeights addObject:@(EWDefaultEdgeInsets.top)];
    }
    
    //清除之前所有的佈局屬性
    [self.attrsArr removeAllObjects];
    
    //開始建立每一個cell對應的佈局屬性
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    for (int i = 0; i < count; i++) {
        
        //建立位置
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        
        //獲取indexPath位置上cell對應的佈局屬性
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
        
        [self.attrsArr addObject:attrs];
    }
}
/**
 * 返回indexPath位置cell對應的佈局屬性
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    //建立佈局屬性
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    //collectionView的寬度
    CGFloat collectionViewW = self.collectionView.frame.size.width;
    //設定佈局屬性的frame
    CGFloat cellW = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;
    CGFloat cellH = [self.delegate waterFallLayout:self heightForItemAtIndexPath:indexPath.item itemWidth:cellW];
    //找出最短的那一列
    NSInteger destColumn = 0;
    CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
    for (int i = 0; i < self.columnCount; i++) {
        //取得第i列的高度
        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
        if (minColumnHeight > columnHeight) {
            minColumnHeight = columnHeight;
            destColumn = i;
        }
    }
    CGFloat cellX = self.edgeInsets.left + destColumn * (cellW + self.columnMargin);
    CGFloat cellY = minColumnHeight;
    if (cellY != self.edgeInsets.top) {
        cellY += self.rowMargin;
    }
    attrs.frame = CGRectMake(cellX, cellY, cellW, cellH);
    //更新最短那一列的高度
    self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
    //記錄內容的高度 - 即最長那一列的高度
    CGFloat maxColumnHeight = [self.columnHeights[destColumn] doubleValue];
    if (self.contentHeight < maxColumnHeight) {
        self.contentHeight = maxColumnHeight;
    }
    return attrs;
}

/**
 * 決定cell的佈局屬性
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attrsArr;
}

/**
 * 內容的高度
 */
- (CGSize)collectionViewContentSize {
    return CGSizeMake(0, self.contentHeight + self.edgeInsets.bottom);
}

@end

實現的效果


用的隨機色出現的配色,好喜歡啊啊啊啊啊~比心比心~

嗯,今天的學習就先到這裡啦,希望可以幫助到你們哦~~~