需求:一個 `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()
}
}
}
進階場景:若邏輯極其複雜,建議拆分為兩個 `UITableViewController` 通過 Container View 嵌入,職責更清晰。