# Membuat TabBar dan Navigation Controller Secara Programatik di UIKit

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

Saya selalu cenderung memilih pendekatan programatik saat mengembangkan aplikasi mobile iOS dengan UIKit. Storyboard mungkin terlihat praktis di awal, tetapi storyboard membuat saya merasa lebih seperti desainer daripada programmer. Selain itu, dalam hal skalabilitas dan kemudahan pengelolaan, saya selalu mendapati pendekatan programatik lebih unggul.

Dalam artikel ini, saya akan menjelaskan proses membuat tab bar controller yang dikombinasikan dengan navigation controller menggunakan UIKit.

### Menyiapkan SceneDelegate

Langkah pertama untuk memakai pendekatan programatik adalah mengubah kode root aplikasi kita. Saya menyebutnya “root”, dan ini mengingatkan saya pada App.js atau index.js di React/React Native. Bagian ini berfungsi sebagai titik masuk aplikasi atau scene kita. Di iOS, kita bisa menemukan fungsi scene di dalam class SceneDelegate, yang akan kita gunakan hanya untuk mengonfigurasi aplikasi agar bisa dikembangkan secara programatik.

Berikut struktur default dari 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.
      }
    }
```

Kita hanya akan mengubah fungsi di bawah ini:

```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 }
  }
```

### Mengubah fungsi scene di SceneDelegate

Pada potongan kode berikut, kita memastikan windowScene diambil dengan aman menggunakan statement guard. Setelah itu, kita memasang windowScene ini ke properti window, yang didefinisikan di dalam class SceneDelegate. Terakhir, kita memanggil method makeKeyAndVisible agar window tersebut menjadi 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()
}
```

Selanjutnya, mari fokus membuat tab bar controller. Controller ini akan menangani view controller untuk setiap tab di aplikasi kita. **_Misalnya, jika kita punya dua tab, kita butuh dua navigation controller yang terpisah._** Tapi kenapa kita memilih navigation controller? Karena kita ingin setiap tab memiliki navigation controller sendiri. Ambil tab “Profile” sebagai contoh. Layar profil akan menjadi view utama untuk tab itu, tetapi mungkin ada view tambahan di dalam tab tersebut yang ingin kita navigasikan. Itulah alasan kita memakai navigation controller untuk setiap item tab. Navigation controller menyediakan fungsi yang dibutuhkan untuk berpindah dengan mulus antara view controller yang berbeda di dalam satu tab.

Ayo kita tulis kodenya!

```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

  }
```

Setelah menginisialisasi tab bar controller, kita membuat dua navigation controller, sesuai dengan dua item tab di aplikasi kita. View controller pertama adalah view controller default, sedangkan view controller kedua, yaitu SecondViewController, akan dibahas di bagian berikutnya. SecondViewController adalah view controller biasa yang mirip dengan yang default.

Untuk mengonfigurasi item tab, kita mengatur properti tabItem dari setiap navigation controller menggunakan UITabBarItem.

Terakhir, kita memasang view controller yang sudah dibuat ke properti viewControllers milik tab bar controller.

Dan langkah yang paling penting adalah mengatur rootViewController milik window menjadi tab bar controller kita. Dengan begitu, tab bar beserta navigation controller di setiap item tab berada di puncak hierarki aplikasi kita.

### View Controller beraksi

Mari kita lihat class ViewController kita di bawah ini:

```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
    }

}
```

Lalu, SecondViewController (_iya, saya tahu, penamaannya memang buruk…_)

![“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
    }

}
```

> Jelas, kodenya cukup berulang. Tapi untuk keperluan artikel ini, hal itu bisa diabaikan.

Kedua view controller ini pada dasarnya identik, kecuali judul dan aksi tombolnya. Keduanya terutama menampilkan label di tengah layar yang menyebutkan nama layar saat ini. Selain itu, keduanya punya tombol di bagian bawah layar untuk berpindah antar item tab. Itulah fungsi inti dari kedua view controller ini.

### Gambaran akhir

Sekarang kita punya aplikasi yang sepenuhnya programatik, memakai tab bar dan navigation controller, tanpa satu pun storyboard!

![Memang jelek tapi berfungsi](https://cdn-images-1.medium.com/max/2000/1*Mh9-aPrme1BRh4QRjRhkVw.gif)

### Kesimpulan

Kesimpulannya, pendekatan programatik memberikan kontrol yang lebih besar atas desain dan skalabilitas aplikasi, sehingga developer bisa fokus pada sisi pemrograman alih-alih bergantung sepenuhnya pada storyboard. Khususnya untuk masalah IBAction/IBOutlet. Salah satu masalah yang muncul saat melakukan refactor pada kode yang melibatkan variabel IBOutlet dan IBAction adalah kebutuhan untuk menyambungkan ulang koneksinya setelah ada perubahan. Dari pengalaman saya, setelah beberapa hari mengerjakan codebase, aplikasi tiba-tiba crash tanpa penjelasan yang jelas. Setelah diselidiki lebih lanjut, saya menemukan bahwa penyebab crash tersebut adalah nama variabel IBOutlet dan IBAction yang diganti. Setiap kali ini terjadi, saya harus menyambungkan ulang variabel yang terdampak secara manual agar fungsinya kembali. Proses ini bisa memakan waktu, membuat frustrasi, dan mengganggu alur kerja pengembangan.

Terima kasih sudah membaca!

```

```

