# Tạo TabBar và Navigation Controller bằng code trong UIKit

By Tarik Pinarci (https://tarikpinarci.com). Published 2023-05-11. Canonical: https://tarikpinarci.com/vi/blog/creating-tabbar-and-navigation-controller-programmatically-in-uikit

Tôi luôn thích cách tiếp cận viết UI bằng code khi phát triển app iOS với UIKit. Storyboard lúc đầu có thể trông tiện lợi, nhưng chúng thường khiến tôi cảm thấy mình giống một designer hơn là một lập trình viên. Hơn nữa, xét về khả năng mở rộng và quản lý, tôi luôn thấy cách viết bằng code tốt hơn.

Trong phạm vi bài viết này, tôi sẽ trình bày chi tiết quá trình tạo một tab bar controller kết hợp với navigation controller bằng UIKit.

### Thiết lập SceneDelegate

Bước đầu tiên để chuyển sang cách viết bằng code là sửa phần code gốc của ứng dụng. Tôi gọi nó là "gốc" (root) và nó làm tôi nhớ đến App.js hoặc index.js trong React/React Native. Đây là điểm khởi đầu (entry point) của ứng dụng hay scene của chúng ta. Trong iOS, chúng ta có thể tìm thấy hàm scene bên trong class SceneDelegate, và chúng ta sẽ chỉ dùng nó để cấu hình ứng dụng theo cách viết bằng code.

Dưới đây là cấu trúc mặc định của class SceneDelegate:

```swift
    import UIKit

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {

      var window: UIWindow?


      func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
      }

      func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
      }

      func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
      }

      func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
      }

      func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
      }

      func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
      }
    }
```

Chúng ta sẽ chỉ cập nhật hàm dưới đây:

```swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
    guard let _ = (scene as? UIWindowScene) else { return }
  }
```

### Cập nhật hàm scene trong SceneDelegate

Trong đoạn code sau, chúng ta lấy windowScene một cách an toàn bằng câu lệnh guard. Sau đó, chúng ta gán windowScene này cho thuộc tính window, được khai báo bên trong class SceneDelegate. Cuối cùng, chúng ta gọi phương thức makeKeyAndVisible để biến window thành key window.

```swift
var window: UIWindow?

func scene(\_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window?.windowScene = windowScene
window?.makeKeyAndVisible()
}
```

Tiếp theo, hãy tập trung vào việc tạo tab bar controller. Controller này sẽ quản lý các view controller cho từng tab trong app. **_Ví dụ, nếu có hai tab, chúng ta sẽ cần hai navigation controller riêng biệt._** Nhưng tại sao lại chọn navigation controller? Đó là vì chúng ta muốn mỗi tab có navigation controller riêng. Lấy tab "Profile" làm ví dụ. Màn hình profile sẽ là view chính của tab đó, nhưng có thể còn những view khác trong tab mà chúng ta muốn điều hướng qua lại. Đó là lý do chúng ta dùng navigation controller cho mỗi tab item. Chúng cung cấp chức năng cần thiết để điều hướng mượt mà giữa các view controller khác nhau trong một tab.

Cùng code thôi!

```swift
 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    window?.windowScene = windowScene
    window?.makeKeyAndVisible()

    let tabbar = UITabBarController()

    let firstVC = UINavigationController(rootViewController: ViewController())
    let secondVC = UINavigationController(rootViewController: SecondViewController())


    firstVC.tabBarItem = UITabBarItem(title: "Home", image: UIImage(systemName: "house"),selectedImage: UIImage(systemName: "house.fill"))

    secondVC.tabBarItem = UITabBarItem(title: "Profile", image: UIImage(systemName: "person"),selectedImage: UIImage(systemName: "person.fill"))

    tabbar.viewControllers = [firstVC, secondVC]

    window?.rootViewController = tabbar

  }
```

Sau khi khởi tạo tab bar controller, chúng ta tạo hai navigation controller, tương ứng với hai tab item trong app. View controller đầu tiên là view controller mặc định, còn view controller thứ hai, tên là SecondViewController, sẽ được nói đến ở phần sau. SecondViewController là một view controller bình thường, giống với view controller mặc định.

Để cấu hình các tab item, chúng ta đặt thuộc tính tabItem của mỗi navigation controller bằng UITabBarItem.

Cuối cùng, chúng ta gán các view controller đã tạo cho thuộc tính viewControllers của tab bar controller.

Và bước quan trọng nhất là đặt rootViewController của window thành tab bar controller của chúng ta. Điều này đảm bảo tab bar, cùng với các navigation controller bên trong mỗi tab item, nằm ở cấp cao nhất trong cây phân cấp của app.

### Các View Controller hoạt động thế nào

Hãy xem class ViewController của chúng ta dưới đây:

```swift
class ViewController: UIViewController {

    override func viewDidLoad() {
      super.viewDidLoad()
      setupUI()
    }

    func setupUI(){
      view.backgroundColor = .white

      let homeLabel: UILabel = {
        let label = UILabel()
        label.text = "This is home screen"
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
      }()

      let homeButton: UIButton = {
        let button = UIButton()
        button.setTitle("Go to profile", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .systemOrange
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(goToProfile), for: .touchUpInside)
        return button
      }()

      view.addSubview(homeButton)
      view.addSubview(homeLabel)


      NSLayoutConstraint.activate([
        homeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        homeButton.widthAnchor.constraint(equalTo: view.widthAnchor),
        homeButton.heightAnchor.constraint(equalToConstant: 72),
        homeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        homeLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
      ])

    }

    @objc func goToProfile(){
      tabBarController?.selectedIndex = 1
    }

}
```

Và đây là SecondViewController (_tôi biết, cách đặt tên ở đây hơi tệ…_)

![“SecondViewController”](https://cdn-images-1.medium.com/max/2000/1*38H_rYXGqsbZNlvJXlyWpg.gif)

```swift
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}

    func setupUI(){
      view.backgroundColor = .white

      let profileLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "This is profile screen"
        return label
      }()

      let profileButton: UIButton = {
        let button = UIButton()
        button.setTitle("Go to home", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.backgroundColor = .systemOrange
        button.translatesAutoresizingMaskIntoConstraints = false
        button.addTarget(self, action: #selector(goToHome), for: .touchUpInside)
        return button
      }()

      view.addSubview(profileButton)
      view.addSubview(profileLabel)

      NSLayoutConstraint.activate([
        homeButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        homeButton.widthAnchor.constraint(equalTo: view.widthAnchor),
        homeButton.heightAnchor.constraint(equalToConstant: 72),
        homeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        homeLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor)
      ])

    }

    @objc func goToHome(){
      tabBarController?.selectedIndex = 0
    }

}
```

> Rõ ràng là code khá lặp lại. Nhưng có thể bỏ qua điều đó trong phạm vi bài viết này.

Hai view controller này về cơ bản giống hệt nhau, chỉ khác tiêu đề và hành động của button. Cả hai chủ yếu render một label ở giữa màn hình, ghi tên của màn hình hiện tại. Ngoài ra, chúng có một button ở cuối màn hình để chuyển qua lại giữa các tab item. Đó là toàn bộ chức năng cốt lõi của hai view controller này.

### Bức tranh cuối cùng

Giờ chúng ta đã có một app viết hoàn toàn bằng code, dùng tab bar và navigation controller, không có lấy một storyboard nào!

![Đúng là xấu nhưng chạy được](https://cdn-images-1.medium.com/max/2000/1*Mh9-aPrme1BRh4QRjRhkVw.gif)

### Kết luận

Tóm lại, viết UI bằng code cho bạn nhiều quyền kiểm soát hơn với thiết kế và khả năng mở rộng của app, giúp lập trình viên tập trung vào phần lập trình thay vì chỉ dựa vào storyboard. Đặc biệt là với các vấn đề về IBAction/IBOutlet**. **Một vấn đề cụ thể xuất hiện khi refactor code có các biến IBOutlet và IBAction là phải kết nối lại sau mỗi lần thay đổi. Theo kinh nghiệm của tôi, sau vài ngày làm việc với codebase, app bắt đầu crash bất ngờ mà không có lời giải thích rõ ràng. Khi tìm hiểu kỹ hơn, tôi phát hiện nguyên nhân là do tên các biến IBOutlet và IBAction đã bị đổi. Mỗi lần như vậy, tôi phải kết nối lại thủ công các biến bị ảnh hưởng để chúng hoạt động trở lại. Đây có thể là một quá trình tốn thời gian và gây bực bội, làm gián đoạn luồng làm việc.

Cảm ơn bạn đã đọc!

```

```

