您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

UICollectionView 詳解:FlowLayout 配置、Cell 重用與頭尾視圖

編輯:iOS 開發綜合

UICollectionView 是 iOS 上最靈活的容器控制項——方格、瀑布流、橫向書架、自訂轉場,全都靠它。可以把它理解為「可多欄、可自訂版型」的 UITableView。以下用一個完整範例走過所有必要環節。

三個核心組成

  • UICollectionView——容器本身,負責管理可捲動內容
  • UICollectionViewLayout——決定每一格的位置與尺寸;系統內建 UICollectionViewFlowLayout
  • DataSource / Delegate——提供資料與回應互動

完整實作

#import "ViewC.h"
#import "CLCollectionViewCell.h"
#import "HeadView.h"
#import "FootView.h"

static NSString *cellIdentifier   = @"cell";
static NSString *headerIdentifier = @"header";
static NSString *footerIdentifier = @"footer";

@interface ViewC () <UICollectionViewDataSource,
                    UICollectionViewDelegate,
                    UICollectionViewDelegateFlowLayout>
@end

@implementation ViewC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor lightGrayColor];

    // 1. 建立並設定 FlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical; // 捲動方向
    flowLayout.minimumLineSpacing = 10.0;      // 列間距(最小值)
    flowLayout.minimumInteritemSpacing = 50.0; // 同列間距(最小值)
    flowLayout.itemSize = CGSizeMake(50, 50);  // 每格尺寸
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10); // section 內縮邊距
    flowLayout.headerReferenceSize = CGSizeMake(320, 20);
    flowLayout.footerReferenceSize = CGSizeMake(320, 20);

    // 2. 建立 collectionView,第二個參數就是版型配置
    UICollectionView *collectionView =
        [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)
                           collectionViewLayout:flowLayout];

    collectionView.dataSource   = self;
    collectionView.delegate     = self;
    collectionView.backgroundColor = [UIColor orangeColor];

    // 3. 註冊重用:cell
    [collectionView registerClass:[CLCollectionViewCell class]
       forCellWithReuseIdentifier:cellIdentifier];

    // 4. 註冊重用:區段頭與尾
    //    參數二指定是 header 還是 footer
    [collectionView registerClass:[HeadView class]
       forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
              withReuseIdentifier:headerIdentifier];

    [collectionView registerClass:[FootView class]
       forSupplementaryViewOfKind:UICollectionElementKindSectionFooter
              withReuseIdentifier:footerIdentifier];

    [self.view addSubview:collectionView];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 10;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section
{
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 從重用池取用;若池中空無一物,系統會依先前註冊的類別自動建立
    CLCollectionViewCell *cell =
        [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier
                                                 forIndexPath:indexPath];
    cell.backgroundColor = [UIColor yellowColor];
    cell.textLabel.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
          viewForSupplementaryElementOfKind:(NSString *)kind
                        atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        HeadView *headerView =
            [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                              withReuseIdentifier:headerIdentifier
                                                     forIndexPath:indexPath];
        headerView.textLabel.text = @"讓我組成頭部!";
        headerView.textLabel.textAlignment = NSTextAlignmentCenter;
        headerView.textLabel.textColor = [UIColor whiteColor];
        return headerView;
    }

    FootView *footerView =
        [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                          withReuseIdentifier:footerIdentifier
                                                 forIndexPath:indexPath];
    footerView.textLabel.text = @"讓我組成尾部!";
    footerView.textLabel.textAlignment = NSTextAlignmentCenter;
    footerView.textLabel.textColor = [UIColor whiteColor];
    return footerView;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView
        didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld %ld", (long)indexPath.section, (long)indexPath.row);
}

#pragma mark - UICollectionViewDelegateFlowLayout(可選)

// 若想讓每一格尺寸不同,實作這個方法即可覆蓋 flowLayout.itemSize
/*
- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                        layout:(UICollectionViewLayout *)collectionViewLayout
  insetForSectionAtIndex:(NSInteger)section;

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section;

- (CGFloat)collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForHeaderInSection:(NSInteger)section;

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForFooterInSection:(NSInteger)section;
*/

@end

關鍵觀念說明

1. 重用機制

dequeueReusableCellWithReuseIdentifier:forIndexPath: 的運作方式和 UITableView 一樣:從重用池中找回收的 cell 重複使用。系統會依 indexPath 判斷池中有沒有可用物件,有就直接給你,沒有才建立新的。務必先註冊再 dequeue,否則會拿到 nil 或觸發例外。

2. 補充視圖(Supplementary View)

header 與 footer 在 API 中屬於「補充視圖」,必須透過 viewForSupplementaryElementOfKind:atIndexPath: 提供,並以 UICollectionElementKindSectionHeader / ...SectionFooter 區分。這與 cell 走不同的 dequeue 方法,是初學者常搞混的地方。

3. FlowLayout 的間距是「最小值」

minimumLineSpacing 與 minimumInteritemSpacing 都是下限而非固定值。當列上還有剩餘空間時,FlowLayout 會把格子撐開填滿(除非你實作 delegate 方法回傳不同的間距)。這也是為什麼有時候設了 10 卻看起來間距更大。

實務上的重點提醒

  • ARC 寫法:範例原始碼是 MRC 風格(含 release),搬進現代專案時請移除所有手動 release,改用 ARC。
  • 註冊 xib 或 code:若 cell 用 xib 排版,改用 registerNib:forCellWithReuseIdentifier:。
  • 異步圖片:cell 中載入網路圖片時,記得在 prepareForReuse 中取消前一次請求,否則快速捲動會出現圖片錯位。
  • 常客 API 別忘了:performBatchUpdates: 做批次增刪、scrollToItemAtIndexPath:atScrollPosition:animated: 定位、UICollectionViewCompositionalLayout(iOS 13+)做更複雜的多區段版型。
  • 效能:cell 的 contentView 層級不宜過深;避免在 cellForItemAtIndexPath: 中做重運算或同步 I/O。

理解「Layout 決定位置、DataSource 提供內容、Delegate 回應互動」這三者的分工之後,不論是簡單網格還是複雜瀑布流,都是同一套骨架上的不同設定。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved