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

iOS Swift 同屏雙 TableView 協調模式實現指南

     編輯:程式設計綜合問答

需求:一個 `UIViewController` 容納兩個 `UITableView`,點擊上方列表刷新下方列表數據。

架構設計

單一 ViewController 作為雙 TableView 的 `dataSource` 和 `delegate`,通過實例引用區分身份。

核心代碼結構

class DualTableVC: UIViewController {
    @IBOutlet weak var topTableView: UITableView!
    @IBOutlet weak var bottomTableView: UITableView!
    
    var topData = [String]()
    var bottomData = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        topTableView.dataSource = self
        topTableView.delegate = self
        bottomTableView.dataSource = self
        bottomTableView.delegate = self
    }
}

extension DualTableVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableView == topTableView ? topData.count : bottomData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
        cell.textLabel?.text = tableView == topTableView ? topData[indexPath.row] : bottomData[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView == topTableView {
            // 根據選中項更新底部數據
            bottomData = fetchDataFor(topData[indexPath.row])
            bottomTableView.reloadData()
        }
    }
}

關鍵點總結

  1. Frame 布局:Storyboard/XIB 中垂直堆疊兩個 TableView,設置約束。
  2. 身份判斷:回調方法中用 `tableView == topTableView` 區分,而非 tag(更類型安全)。
  3. 數據驅動:上層選中觸發模型更新 → `reloadData()` 刷新下層視圖。

進階場景:若邏輯極其複雜,建議拆分為兩個 `UITableViewController` 通過 Container View 嵌入,職責更清晰。

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