前面我們談到 UITableView 系統預建的 image、textLabel、detailTextLabel,用起來很方便,但限制也多——位置不能改、樣式不能客製。這一篇要介紹自訂單元格,讓你可以完全掌控 cell 顯示什麼內容、放在哪裡、長什麼樣子。
以下要製作一個球星列表,每筆資料包含四項資訊:頭像、姓名、年齡、性別。
![]()
從物件庫把需要的控制項拖進 cell 上,依版面需求擺放:
列高(row height):設定 UITableView 的 rowHeight,這是 table view 每一列實際佔掉的高度。不論你的 cell 內容多高,畫面上永遠只給這麼多。
cell 高度:cell 本身的高度。若要支援自適應,實作 tableView:heightForRowAtIndexPath: 或改用 UITableViewAutomaticDimension 搭配 estimatedRowHeight。
在 Attributes Inspector 中為 cell 填入 Identifier,稍後在程式碼中用它來 dequeue:
新增一個繼承自 UITableViewCell 的類別,並把剛才拖上去的控制項關聯為 IBOutlet:
#import <UIKit/UIKit.h> @interface CustomTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *image; @property (weak, nonatomic) IBOutlet UILabel *name; @property (weak, nonatomic) IBOutlet UILabel *age; @property (weak, nonatomic) IBOutlet UILabel *phone; @end
接著回到 storyboard,選取那個 cell,在 Identity Inspector 的 Custom Class 中指定為 CustomTableViewCell,這樣 outlet 才連得上:
#import "CustomTableViewController.h"
#import "CustomTableViewCell.h"
@interface CustomTableViewController () <UITableViewDataSource>
@end
@implementation CustomTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"Cell";
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.name.text = @"科比";
cell.age.text = @"37";
cell.phone.text = @"男";
cell.image.image = [UIImage imageNamed:@"Kobe.png"];
return cell;
}
@end
圖片要依 row 取值,而不是寫死。範例為求簡潔直接指定 Kobe.png,真實專案應從資料來源陣列取出 indexPath.row 對應的 model,否則每一列都會長得一樣。
別忘了處理重用造成的殘留。cell 會被重複利用,若某列沒有頭像、某列沒有副標,上一次的內容會殘留。務必在 cellForRowAtIndexPath: 中「無論有無資料都明確賦值」,例如在沒有圖片時設 cell.image.image = nil;,或改在自訂 cell 中覆寫 prepareForReuse 做重置。
IBOutlet 建議加上 weak 與 IBOutlet 的宣告順序。storyboard 已經持有這些子視圖,property 用 weak 即可,避免多餘的強引用。命名上也建議加上前綴,方便辨識來源。
用 dequeue 而非每次 alloc。範例已正確使用 dequeueReusableCellWithIdentifier:。若 cell 可能不存在(例如尚未在 storyboard 註冊 identifier),改用 dequeueReusableCellWithIdentifier:forIndexPath: 會由系統保證非 nil,程式碼更乾淨。
自適應高度的現代寫法。在 viewDidLoad 中設定 tableView.rowHeight = UITableViewAutomaticDimension; 與 tableView.estimatedRowHeight = 100;,然後在 cell 內部讓 Auto Layout 約束完整地從頂端連到基底,系統就會依內容自動算出高度,不必再手寫 heightForRow。
自訂 cell 是 iOS 列表開發的核心技能。掌握它之後,再搭配 XIB 獨立管理版面、或用 Cell 的 accessoryView 與 editingStyle 客製化互動,就能應付絕大多數的列表需求。