對熟悉 UITableView 的開發者來說,UICollectionView 的資料來源與委派概念並不陌生。它同樣以 section 與 item 為核心,透過 dequeue 機制重用 Cell,並由 view controller 提供每一格要顯示的內容。
若使用 Storyboard,最重要的步驟是確認 delegate 與 datasource 有正確連線到 view controller,也別忘了 collection view 與自訂 cell 的 identifier 要一致。若沒有使用 Auto Layout,也要先取消勾選,避免後續 frame 計算被系統接管。
如果 Cell 內部元件不複雜,可以直接在 Cell 上為每個子檢視設定 tag,再利用 viewWithTag 取得元件。這種方式適合快速驗證畫面,但正式專案仍建議建立獨立 Cell 類別,讓資料綁定更清楚。
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
{
return 6;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"imgCell" forIndexPath:indexPath];
UILabel *titleLabel = (UILabel *)[cell viewWithTag:11];
NSString *sttr = [NSString stringWithFormat:@"Hello~%d", indexPath.row];
[titleLabel setText:sttr];
return cell;
}
當 Cell 被點選並觸發 segue 時,可在 prepareForSegue 中判斷 segue identifier,再把 indexPath 或模型物件傳給目標 controller。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"])
{
// 在這裡把資料傳給下一個視圖
}
}