UITableViewController và UIViewController là 2 class khác nhau trong UIKit, phục vụ mục đích khác nhau.
UIViewController (Base Class)
- Quản lý một View** đơn lẻ (root view).
- Xử lý vòng đời view:
viewDidLoad,viewWillAppear,viewDidAppear,viewWillDisappear,viewDidDisappear. - Chịu trách nhiệm layout, rotation, memory management cho view của nó.
- Dùng khi màn hình có nhiều loại view khác nhau (label, button, image, map, collection view...).
class ViewController: UIViewController {
@IBOutlet weak var customView: UIView!
override func viewDidLoad() { super.viewDidLoad() }
}
UITableViewController (Subclass chuyên biệt)
- Kế thừa
UIViewController. - Root view là một UITableView (property
tableViewsẵn có). - Tự conform
UITableViewDataSourcevàUITableViewDelegate. - Tự động xử lý: reload data khi xuất hiện, clear selection, flash scroll indicators.
- Dùng khi màn hình chỉ chứa Table View (danh sách, settings, feed...).
class MyTableVC: UITableViewController {
override func viewDidLoad() { super.viewDidLoad() }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
}
UIViewController + Table View (Phổ biến hơn)
Nếu màn hình có Table View kết hợp với view khác (header, footer, button, search bar...), dùng UIViewController + conform protocols:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var headerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { ... }
}
Bảng so sánh
| Đặc điểm | UIViewController | UITableViewController |
|---|---|---|
| Root View | UIView (tùy chỉnh) | UITableView (fixed) |
| DataSource/Delegate | Tự implement | Sẵn có (self) |
| Auto reload data | Không | Có (viewWillAppear) |
| Auto clear selection | Không | Có (viewWillAppear) |
| Flash scroll indicators | Không | Có (viewDidAppear) |
| Phù hợp | Màn hình phức tạp, mixed views | Màn hình chỉ là danh sách |
Khuyến nghị: Hầu hết trường hợp dùng UIViewController + UITableView outlet để linh hoạt. Chỉ dùng UITableViewController cho màn hình danh sách đơn thuần, full-screen.