UICollectionView 可以理解為「可客製化的多列多欄版 UITableView」,是編排圖片牆、卡片流、分頁選單的首選。它比 UITableView 複雜,但一旦掌握,很多原本要靠多個 tableView 聯動才能做出的效果都會變得簡單。
基本使用需要遵循 UICollectionViewDelegate、UICollectionViewDataSource 與 UICollectionViewDelegateFlowLayout。前兩個用法與 UITableView 幾乎一致,第三個則是 UICollectionView 獨有的佈局協議,用來回報單元格尺寸與頭尾視圖資訊。
特別提醒:頭視圖與尾視圖都必須先註冊,否則 dequeueReusableSupplementaryViewOfKind: 會直接崩潰。註冊之後復用機制會自動接管,不必再手動管理。
// 建立佈局對象
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
// 單元格尺寸
flowLayout.itemSize = CGSizeMake(80, 80);
// 頭視圖高度
flowLayout.headerReferenceSize = CGSizeMake(0, 30);
// 橫向滾動
flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
_myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 200, 320, 280)
collectionViewLayout:flowLayout];
_myCollectionView.tag = 200;
_myCollectionView.backgroundColor = [UIColor greenColor];
_myCollectionView.delegate = self;
_myCollectionView.dataSource = self;
[self.view addSubview:_myCollectionView];
// 註冊 cell
[_myCollectionView registerClass:[UICollectionViewCell class]
forCellWithReuseIdentifier:@"myheheIdentifier"];
// 註冊頭視圖(這一步很容易被漏掉)
[_myCollectionView registerClass:[UICollectionReusableView class]
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:@"Identifierhead"];
#pragma mark - UICollectionViewDataSource
// 組(section)的數量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 2;
}
// 每一組裡的項目數量
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
return 10;
}
// 建立單元格
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
if (collectionView.tag == 200) {
UICollectionViewCell *cell =
[collectionView dequeueReusableCellWithReuseIdentifier:@"myheheIdentifier"
forIndexPath:indexPath];
cell.backgroundColor = [UIColor purpleColor];
return cell;
}
return nil;
}
// 建立組的頭視圖
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSString *)kind
atIndexPath:(NSIndexPath *)indexPath {
UICollectionReusableView *headView =
[collectionView dequeueReusableSupplementaryViewOfKind:kind
withReuseIdentifier:@"Identifierhead"
forIndexPath:indexPath];
headView.backgroundColor = [UIColor blueColor];
return headView;
}
#pragma mark - UICollectionViewDelegateFlowLayout
// 動態計算單元格尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
CGFloat rd = arc4random() % 90;
return CGSizeMake(90, rd);
}
如果要用 UITableView 做出「表頭懸浮 + 內容聯動」的效果,往往需要多個列表互相觀察、用 contentOffset 手動同步滾動,邏輯脆弱且難以維護。UICollectionView 的 supplementary view 天生支援懸浮,多組內容在同一個滾動視圖內自然聯動,代碼量與出錯機率都大幅下降。