# Creare TabBar e navigation controller via codice in UIKit

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

Quando sviluppo app iOS con UIKit ho sempre preferito l'approccio via codice. Gli storyboard all'inizio possono sembrare comodi, ma mi fanno sentire più un designer che un programmatore. Inoltre, quando si parla di scalabilità e manutenibilità, trovo sempre che l'approccio via codice sia migliore.

In questo articolo spiego come creare un tab bar controller combinato con un navigation controller usando UIKit.

### Configurare SceneDelegate

Il primo passo per adottare l'approccio via codice è modificare il codice "radice" della nostra applicazione. Lo chiamo "radice" perché mi ricorda App.js o index.js in React/React Native. È il punto di ingresso della nostra applicazione, o della scena. In iOS troviamo una funzione scene dentro la classe SceneDelegate, che useremo solo per configurare l'applicazione allo sviluppo via codice.

Ecco la struttura predefinita della classe 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.
      }
    }
```

Aggiorneremo solo la funzione qui sotto:

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

### Aggiornare la funzione scene in SceneDelegate

Nello snippet seguente recuperiamo in modo sicuro la windowScene con l'istruzione guard. Poi assegniamo questa windowScene alla proprietà window, definita nella classe SceneDelegate. Infine chiamiamo il metodo makeKeyAndVisible per rendere la window la 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()
}
```

Ora concentriamoci sulla creazione del tab bar controller. Questo controller gestirà i view controller di ogni tab dell'app. **_Per esempio, se abbiamo due tab, ci serviranno due navigation controller separati._** Ma perché proprio i navigation controller? Perché vogliamo che ogni tab abbia il suo navigation controller. Prendiamo come esempio il tab "Profile". La schermata del profilo sarà la vista principale di quel tab, ma dentro il tab potremmo avere altre viste tra cui vogliamo navigare. Ecco perché usiamo un navigation controller per ogni elemento della tab bar: forniscono quello che serve per muoversi senza intoppi tra i diversi view controller di un tab.

Scriviamo il codice!

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

  }
```

Dopo aver inizializzato il tab bar controller, creiamo due navigation controller, che corrispondono ai due elementi della tab bar della nostra app. Il primo view controller è quello predefinito, mentre il secondo, chiamato SecondViewController, lo vediamo nella prossima sezione. SecondViewController è un normale view controller simile a quello predefinito.

Per configurare gli elementi della tab bar impostiamo la proprietà tabItem di ogni navigation controller usando UITabBarItem.

Infine assegniamo i view controller creati alla proprietà viewControllers del tab bar controller.

E il passo più importante è impostare il rootViewController della window sul nostro tab bar controller. Così la tab bar, insieme ai navigation controller di ogni tab, sta in cima alla gerarchia dell'app.

### I view controller in azione

Diamo un'occhiata alla nostra classe ViewController qui sotto:

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

}
```

E poi SecondViewController (_lo so, nome scelto malissimo…_)

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

}
```

> Ovviamente il codice è piuttosto ripetitivo. Ma per lo scopo di questo articolo possiamo ignorarlo.

Questi due view controller sono praticamente identici, a parte i titoli e le azioni dei pulsanti. Entrambi mostrano un'etichetta al centro dello schermo con il nome della schermata corrente. In più hanno un pulsante in fondo allo schermo che permette di spostarsi tra gli elementi della tab bar. Questo riassume il funzionamento di base dei due view controller.

### Il risultato finale

Ora abbiamo un'app interamente scritta via codice che usa tab bar e navigation controller, senza nemmeno uno storyboard!

![Brutta, certo, ma funziona](https://cdn-images-1.medium.com/max/2000/1*Mh9-aPrme1BRh4QRjRhkVw.gif)

### Conclusione

In conclusione, l'approccio via codice dà più controllo sul design e sulla scalabilità dell'app, e permette agli sviluppatori di concentrarsi sulla programmazione invece di affidarsi solo agli storyboard. In particolare per i problemi con IBAction/IBOutlet**. **Un problema tipico quando si fa refactoring di codice con variabili IBOutlet e IBAction è dover ricollegare le connessioni dopo ogni modifica. Nella mia esperienza, dopo qualche giorno di lavoro sulla codebase, l'app ha iniziato a crashare all'improvviso senza una spiegazione chiara. Indagando ho scoperto che la causa erano i nomi delle variabili IBOutlet e IBAction che avevo rinominato. Ogni volta che succedeva dovevo ricollegare a mano le variabili coinvolte per farle funzionare di nuovo. È un processo lungo e frustrante che interrompe il flusso di lavoro.

Grazie per aver letto!

```

```

