在 UICollectionView 裡,自訂 UICollectionViewCell 是常見做法,但如果 Cell 只是顯示一段文字、一個邊框或簡單背景,建立子類別反而讓專案變得零碎。這時可以直接在 collectionView:cellForItemAtIndexPath: 中組裝 Cell。
核心概念是從重用佇列取得基礎 UICollectionViewCell,加入需要的子檢視,再回傳。因為 Cell 會被重用,所以每次取出時都應該先清掉先前加入的 subview,避免文字或邊框重疊。
使用 UICollectionView 時,通常至少要實作 UICollectionViewDataSource、UICollectionViewDelegate 與 UICollectionViewDelegateFlowLayout。
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SimpleCell" forIndexPath:indexPath];
[cell.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(5, 5, cell.width - 10, cell.height - 10)];
UILabel *label = [[UILabel alloc] initWithFrame:borderView.frame];
label.font = [UIFont systemFontOfSize:16];
label.textAlignment = NSTextAlignmentCenter;
label.text = @"示例內容";
[cell addSubview:borderView];
[cell addSubview:label];
return cell;
如果同一個畫面有多種 Cell 樣式,可以用 style 或 enum 做分支,替不同分支設定不同的 reuseIdentifier。重點是每個 reuseIdentifier 都要在註冊或建立時保持一致,並確保子檢視重建前先被移除。
這種做法適合快速原型、靜態選單、簡單標籤格或臨時展示。若 Cell 有複雜排版、動畫、快取需求或大量重用狀態,仍然建議建立專屬的 UICollectionViewCell 子類別,讓程式碼更容易維護。