Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Khác biệt giữa UITableViewController và UIViewController

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 tableView sẵn có).
  • Tự conform UITableViewDataSource và 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ểmUIViewControllerUITableViewController
Root ViewUIView (tùy chỉnh)UITableView (fixed)
DataSource/DelegateTự implementSẵn có (self)
Auto reload dataKhôngCó (viewWillAppear)
Auto clear selectionKhôngCó (viewWillAppear)
Flash scroll indicatorsKhôngCó (viewDidAppear)
Phù hợpMàn hình phức tạp, mixed viewsMà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.