用程式碼建立 UICollectionView,比在 Storyboard 裡拉元件更能看清每個環節的職責。整個過程可以拆成「建立 layout → 建立 collectionView → 註冊 cell → 設定 delegate 與 dataSource → 實作各個回呼」五步。
標頭檔
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate> @end
實作檔
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *identifier = @"cell";
// 1. 建立並設定 layout,決定捲動方向與間距
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
// 也可以設定每個 section 的內距:
// flowLayout.sectionInset = UIEdgeInsetsMake(15, 10, 15, 5);
// 2. 用 layout 初始化 collectionView
UICollectionView *collectionView =
[[UICollectionView alloc] initWithFrame:CGRectMake(0, 30, 320, 480)
collectionViewLayout:flowLayout];
// 3. 註冊可重複使用的 cell
[collectionView registerClass:[UICollectionViewCell class]
forCellWithReuseIdentifier:identifier];
// 4. 設定代理
collectionView.delegate = self;
collectionView.dataSource = self;
[self.view addSubview:collectionView];
}
#pragma mark - UICollectionViewDataSource / Delegate
// section 數量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
// 每個 section 的內距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(30, 15, 30, 15);
}
// 每個 section 的項目數量
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
return 24;
}
// 每個項目的大小
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(140, 160);
}
// 每個項目的內容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell =
[collectionView dequeueReusableCellWithReuseIdentifier:identifier
forIndexPath:indexPath];
cell.backgroundColor = [UIColor greenColor];
return cell;
}
@end幾個容易忽略的細節:UICollectionView 的 dataSource 與 delegate 是兩個不同職責,前者負責「有幾格、內容是什麼」,後者負責互動行為,實作時別只掛一個。另外 cell 一定要透過 dequeueReusableCellWithReuseIdentifier: 取得以維持效能,而 registerClass 裡註冊的 identifier 必須與取用時一致,否則會直接 crash。若需要自訂樣式,則要把 registerClass 換成自訂的 UICollectionViewCell 子類別,並在該子類別中建立 subview。