首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS UITableView 進階:單一 ViewController 管理多個 Table View 的實作技巧

     編輯:程式設計綜合問答

在 iOS 開發中,單一 UIViewController 內放置多個 UITableView 是常見需求(如分頁式列表、並排對比、複雜表單)。關鍵在於如何讓 Delegate/DataSource 方法正確識別是哪一個 Table View 在詢問資料。

核心技巧:使用 tag 屬性區分

1. Storyboard / XIB 設定

  • 拖曳兩個 Table View 到 View Controller
  • 分別設定 tag:Table View 1 → 100,Table View 2 → 200
  • 兩者的 delegate 與 dataSource 都連到 File's Owner(同一個 VC)

2. 程式碼建立

let tableView1 = UITableView()
tableView1.tag = 100
tableView1.delegate = self
tableView1.dataSource = self

let tableView2 = UITableView()
tableView2.tag = 200
tableView2.delegate = self
tableView2.dataSource = self

3. Delegate/DataSource 方法中判斷

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 點擊
    }
}

進階替代方案:獨立 Delegate 物件(更符合單一職責原則)

當邏輯複雜時,將每個 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 類別職責分離、易複用、易單元測試類別數增加、需額外管理生命週期

適用建議

  • 簡單畫面(2-3 個列表、邏輯輕量)→ tag 判斷
  • 複雜畫面(每個列表有獨立邏輯、資料來源、互動)→ 獨立 Delegate 類別
  • 現代 Swift 開發:搭配 DiffableDataSource 更優雅

掌握多 Table View 管理技巧,能讓單一 VC 輕鬆駕馭複雜列表介面,避免程式碼混亂。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved