您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

用自定義 UICollectionViewLayout 實作 iOS 瀑布流

編輯:iOS 程式設計技術

瀑布流是新聞、電商類 App 裡極常見的版面形式。要實現它,關鍵在於理解 UICollectionView 的佈局機制,並動手改寫它的佈局方式。

先認識 UICollectionView

在動手之前,先掌握幾個重點:

  • 它與 tableView 不同,內容視圖的內容需要我們自己添加。
  • 相比 tableView,它的初始化必須搭配一個 FlowLayout,而且絕大多數操作都集中在這個 Layout 上。
  • UICollectionView 實用性極強,雖然並非所有場景下的最佳解,卻能相當靈活地實現各種效果。

如圖所示,模擬器上呈現的是一格格方塊,它們排列得整整齊齊,卻也顯得單調呆板。我們所要做的瀑布流,正是要在保留規律的前提下打破這種整齊,讓每個 cell 高度不一,如同流水般自然錯落。

實現思路

既然 UICollectionView 的大部分操作都在 FlowLayout 上,那麼實現瀑布流的核心,就是改寫它的格局部署邏輯。動手前先理清思路:

  • 先確定瀑布流的顯示風格,再據此進行整體設計,最後透過細節打磨完善代碼。
  • 我們要的正是把原本等高排列的方塊,改造成不等高的效果,讓它像名字一樣有流水般的層次感。
  • 整體上每個模塊仍是一個 cell;要保證最上面一行 cell 的 y 值一致以求美觀;也要避免某一列特別長、某一列特別短的失衡。
  • 由於每個 cell 高度不同,需要考慮放置順序;同時注意精簡代碼。

實現效果

核心代碼

先來看控制器部分,它負責配置 collectionView 與數據源:

// ViewController.m // CX-瀑布流 UICollectionView 實現
#import "ViewController.h"
#import "CXCollectionViewCell.h"
#import "CXCollectionViewLayout.h"
static NSString * identifier = @"cellID";
@interface ViewController ()<UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView * collectionView;
@end
@implementation ViewController
#pragma mark - <懶加載>
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        //初始化自定義的 flowLayout
        CXCollectionViewLayout * flowLayout = [[CXCollectionViewLayout alloc]init];
        _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.dataSource = self;
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CXCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:identifier];
    }
    return _collectionView;
}
#pragma mark - <life>
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
}
#pragma mark - <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 100;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CXCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    cell.label.text = [NSString stringWithFormat:@"%zd",indexPath.item];
    cell.backgroundColor = [UIColor orangeColor];
    return cell;
}
@end

真正的關鍵在自定義的 Layout。它需要重寫準備佈局、返回佈局屬性與計算內容尺寸等方法:

// CXCollectionViewLayout.m // CX-瀑布流 UICollectionView 實現
#import "CXCollectionViewLayout.h"
static NSInteger CXcolumnCount = 3;              //列數
static UIEdgeInsets CXdefaultEdgeInsets = {20,15,10,15}; //內邊距
static NSInteger CXcolumnMagin = 10;            //列間距
static NSInteger CXrowMagin = 10;               //行間距
@interface CXCollectionViewLayout ()
@property (nonatomic, strong) NSMutableArray * CXattrsArray;    //所有 cell 的佈局屬性
@property (nonatomic, strong) NSMutableArray * CXcolumnHeights; //各列高度
@end
@implementation CXCollectionViewLayout
- (NSMutableArray *)CXattrsArray{
    if (!_CXattrsArray) { _CXattrsArray = [NSMutableArray array]; }
    return _CXattrsArray;
}
- (NSMutableArray *)CXcolumnHeights{
    if (!_CXcolumnHeights) { _CXcolumnHeights = [NSMutableArray array]; }
    return _CXcolumnHeights;
}
#pragma mark - <准備佈局>
- (void) prepareLayout{
    [super prepareLayout];
    //每次佈局前清空之前存儲的屬性
    [self.CXcolumnHeights removeAllObjects];
    [self.CXattrsArray removeAllObjects];
    //為第一行各列初始化高度
    for (NSInteger i = 0; i < CXcolumnCount; i ++) {
        [self.CXcolumnHeights addObject:@(CXdefaultEdgeInsets.top)];
    }
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (NSInteger i = 0; i < count; i ++) {
        NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes * attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.CXattrsArray addObject:attributes];
    }
}
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.CXattrsArray;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewLayoutAttributes * CXattributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    CGFloat collectionViewWidth = self.collectionView.frame.size.width;
    CGFloat width;
    CGFloat height;
    CGFloat X;
    CGFloat Y;
    width = (collectionViewWidth - CXdefaultEdgeInsets.left - CXdefaultEdgeInsets.right - (CXcolumnCount - 1) * CXcolumnMagin) / CXcolumnCount;
    //實際開發中 height 由數據決定,此處用 100~150 的隨機數演示原理
    height = 100 + arc4random_uniform(50);
    //找出當前最矮的一列
    NSInteger tempColumn = 0;
    CGFloat minColumnHeight = [self.CXcolumnHeights[0] doubleValue];
    for (NSInteger i = 1; i < CXcolumnCount; i ++) {
        if (minColumnHeight > [self.CXcolumnHeights[i] doubleValue]) {
            minColumnHeight = [self.CXcolumnHeights[i] doubleValue];
            tempColumn = i;
        }
    }
    X = CXdefaultEdgeInsets.left + (width + CXcolumnMagin) * tempColumn;
    Y = minColumnHeight;
    if (Y != CXdefaultEdgeInsets.top) {
        Y += CXrowMagin;
    }
    CXattributes.frame = CGRectMake(X, Y, width, height);
    //更新最矮那一列的高度
    self.CXcolumnHeights[tempColumn] = @(CGRectGetMaxY(CXattributes.frame));
    return CXattributes;
}
- (CGSize)collectionViewContentSize{
    CGFloat maxColumnHeight = [self.CXcolumnHeights[0] doubleValue];
    for (NSInteger i = 1; i < CXcolumnCount; i++) {
        CGFloat columnHeight = [self.CXcolumnHeights[i] doubleValue];
        if (maxColumnHeight < columnHeight) {
            maxColumnHeight = columnHeight;
        }
    }
    return CGSizeMake(0, maxColumnHeight + CXdefaultEdgeInsets.bottom);
}
@end

幾個值得注意的地方

  • 瀑布流中每個 cell 的排布,取決於當前各列的高度。例如第三列此時最矮,即便按常規順序該排到第一列,新 cell 也會落到第三列,以此避免某列過長或過短。
  • 實際應用中,cell 尺寸通常依據真實數據計算,而非隨機。
  • UICollectionView 的內容高度並非固定,需根據內容動態設定。
  • 涉及下拉刷新時,務必確認新數據到來前是否已清空舊的佈局屬性。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved