UICollectionView 的建立方式與 UITableView 大同小異,但把常見設定收攏到子類別中,能讓使用端清爽不少。本文示範如何建立一個自訂的 collectionView 子類,並說明 cell、頭視圖與 flowLayout 的處理。
- (id)initWithFrame:(CGRect)frame {
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.minimumInteritemSpacing = 0; // 列間距
flowLayout.minimumLineSpacing = 0; // 行間距
self = [super initWithFrame:frame collectionViewLayout:flowLayout];
if (self) {
// 隱藏滾動條
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
// 設定代理
self.delegate = self;
self.dataSource = self;
// 設定背景顏色(預設為黑色)
self.backgroundColor = [UIColor whiteColor];
// 註冊單元格
[self registerClass:[YSStudentStatusCell class] forCellWithReuseIdentifier:identify];
}
return self;
}
collectionView 的協議方法與 tableView 幾乎一致,主要差別在於 cell 與頭視圖的建立方式。
// 建立 cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath {
ModelStudent *model = self.dataArray[indexPath.item];
// 子類化的 cell
YSStudentStatusCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify
forIndexPath:indexPath];
[cell configureWithModel:model.StuUserInfo];
return cell;
}
子類化 cell 的初始化方法如下,這裡用 init 不會被呼叫,所以要寫在 initWithFrame: 中:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initView];
}
return self;
}
使用 supplementary view 之前必須先註冊,這一步通常和 cell 註冊寫在同一處:
// collection 頭視圖的註冊
[self registerClass:[UICollectionReusableView class]
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
withReuseIdentifier:@"Identifierhead"];
建立頭視圖的協議方法:
// 組的頭視圖建立
- (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;
}
flowLayout 可以說是 collectionView 的布局靈魂:替換不同的 layout 物件,就能載入完全不同的排列樣式,從簡單的網格到瀑布流、輪播卡片都難不倒它。
實務上還有一個細節:UICollectionViewCell 不像 UITableViewCell 那樣預設自帶 contentView 排版結構,所有子視圖都要自己建立並加上約束;另外它沒有內建的左滑操作與分隔線,這些都需要自行實作。