在 iOS 開發中,單一 UIViewController 內放置多個 UITableView 是常見需求(如分頁式列表、並排對比、複雜表單)。關鍵在於如何讓 Delegate/DataSource 方法正確識別是哪一個 Table View 在詢問資料。
tag:Table View 1 → 100,Table View 2 → 200delegate 與 dataSource 都連到 File's Owner(同一個 VC)let tableView1 = UITableView()
tableView1.tag = 100
tableView1.delegate = self
tableView1.dataSource = self
let tableView2 = UITableView()
tableView2.tag = 200
tableView2.delegate = self
tableView2.dataSource = self
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch tableView.tag {
case 100: return dataSource1.count
case 200: return dataSource2.count
default: return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch tableView.tag {
case 100:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)
cell.textLabel?.text = dataSource1[indexPath.row]
return cell
case 200:
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
cell.textLabel?.text = dataSource2[indexPath.row]
return cell
default:
return UITableViewCell()
}
}
// 點擊事件同理
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableView.tag == 100 {
// 處理列表 1 點擊
} else if tableView.tag == 200 {
// 處理列表 2 點擊
}
}
當邏輯複雜時,將每個 Table View 的 Delegate/DataSource 抽離為獨立類別,VC 僅持有參考:
class FirstTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource {
var data: [String] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { data.count }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ... }
}
// VC 中
let firstDelegate = FirstTableDelegate()
tableView1.delegate = firstDelegate
tableView1.dataSource = firstDelegate
| 方案 | 優點 | 缺點 |
|---|---|---|
| tag 判斷 | 程式碼集中、簡單快速 | 方法膨脹、耦合度高、難測試 |
| 獨立 Delegate 類別 | 職責分離、易複用、易單元測試 | 類別數增加、需額外管理生命週期 |
DiffableDataSource 更優雅掌握多 Table View 管理技巧,能讓單一 VC 輕鬆駕馭複雜列表介面,避免程式碼混亂。