以下示範完全不靠 Storyboard,用程式碼建立一個 UICollectionView。
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate>
{
NSString *identifier;
}
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
identifier = @"cell";
// 1. 初始化 layout
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
// UIEdgeInsets top = {15, 10, 15, 5};
// [flowLayout setSectionInset:top];
// 2. 建立 collectionView 並綁上 layout
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 - UICollectionViewDelegate / DataSource
// 分區數量
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
// 每個分區的內縮邊距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section {
UIEdgeInsets top = {30, 15, 30, 15};
return top;
}
// 每個分區的項目數量
- (NSInteger)collectionView:(UICollectionView *)collectionView
numberOfItemsInSection:(NSInteger)section {
return 24;
}
// 每個項目的內容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
UICollectionViewCell *cell =
[collectionView dequeueReusableCellWithReuseIdentifier:identifier
forIndexPath:indexPath];
[cell sizeToFit];
cell.backgroundColor = [UIColor greenColor];
return cell;
}
// 每個項目的大小
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return CGSizeMake(140, 160);
}
@end
1. 一定要指定 layout。UICollectionView 不像 UITableView 有預設樣式,必須傳入一個 UICollectionViewLayout(實務上幾乎都用 UICollectionViewFlowLayout),否則建構子無法初始化。
2. 必須先註冊再 dequeue。這一步跟 UITableView 一樣,沒註冊就 dequeue 會得到 nil 或直接崩潰。
3. 尺寸由 delegate 決定。sizeForItemAtIndexPath 回傳的是「項目」大小,而 section 的內縮由 insetForSectionAtIndex 控制,兩者共同決定最終排版。
4. 想自訂 cell 外觀,繼承 UICollectionViewCell 並在自訂類別中建立 subview,再替換 registerClass 的參數即可。
補充一點:上面的 cell 只是套用背景色,若要放圖片或文字,記得實作自訂 cell 並在 prepareForReuse 中清掉上一輪的內容,否則在快速滾動時會出現圖文錯位——這是 collectionView 最常見的 bug 來源。