您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS 不自訂 UICollectionViewCell:直接在委派方法完成

編輯:iOS 7 技巧

為什麼有時不需要自訂 Cell

在 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 子類別,讓程式碼更容易維護。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved