# Создаём TabBar и Navigation Controller программно в UIKit

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

Когда я разрабатываю iOS-приложения на UIKit, я всегда склоняюсь к программному подходу. Storyboards поначалу могут казаться удобными, но с ними я чувствую себя скорее дизайнером, чем программистом. К тому же, когда речь заходит о масштабируемости и управляемости, программный подход раз за разом оказывается для меня лучше.

В этой статье я подробно расскажу, как создать tab bar controller в связке с navigation controller на UIKit.

### Настраиваем SceneDelegate

Первый шаг к программному подходу: изменить корневой код приложения. Я называю его «корнем», и он напоминает мне App.js или index.js в React/React Native. Это точка входа для нашего приложения или сцены. В iOS функцию scene можно найти в классе SceneDelegate, и мы будем использовать её только для того, чтобы настроить приложение под программную разработку.

Ниже стандартная структура класса 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.
      }
    }
```

Мы будем менять только эту функцию:

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

### Обновляем функцию scene в SceneDelegate

В следующем фрагменте кода мы безопасно получаем windowScene с помощью оператора guard. Затем присваиваем этот windowScene свойству window, которое объявлено в классе SceneDelegate. И наконец вызываем метод makeKeyAndVisible, чтобы сделать окно ключевым.

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

Теперь займёмся созданием tab bar controller. Этот контроллер будет управлять view controllers для каждой вкладки приложения. **_Например, если у нас две вкладки, нам понадобятся два отдельных navigation controller._** Но почему именно navigation controllers? Потому что мы хотим, чтобы у каждой вкладки был свой собственный navigation controller. Возьмём для примера вкладку «Profile». Экран профиля будет главным экраном этой вкладки, но внутри вкладки могут быть и другие экраны, между которыми нужно переходить. Поэтому для каждого элемента вкладки мы используем navigation controller. Он даёт всё необходимое, чтобы плавно переходить между разными view controllers внутри вкладки.

Давайте напишем код!

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

  }
```

После инициализации tab bar controller мы создаём два navigation controller, по одному на каждую из двух вкладок приложения. Первый view controller стандартный, а второй, SecondViewController, мы разберём в следующем разделе. SecondViewController это обычный view controller, похожий на стандартный.

Чтобы настроить элементы вкладок, мы задаём свойство tabItem у каждого navigation controller через UITabBarItem.

Наконец, присваиваем созданные view controllers свойству viewControllers у tab bar controller.

И самый важный шаг: делаем наш tab bar controller значением rootViewController у window. Так tab bar вместе с navigation controllers внутри каждой вкладки оказывается на вершине иерархии приложения.

### View Controllers в действии

Посмотрим на наш класс ViewController:

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

}
```

И SecondViewController (_да, знаю, название так себе…_)

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

}
```

> Конечно, код довольно однообразный. Но для целей этой статьи этим можно пренебречь.

Эти два view controller по сути одинаковые, отличаются только заголовками и действиями кнопок. Оба в основном выводят по центру экрана label с названием текущего экрана. Кроме того, внизу экрана у них есть кнопка, которая позволяет переходить между вкладками. Вот и вся основная функциональность этих view controllers.

### Итоговая картина

Теперь у нас полностью программное приложение с tab bar и navigation controller, и ни одного storyboard!

![Да, некрасиво, зато работает](https://cdn-images-1.medium.com/max/2000/1*Mh9-aPrme1BRh4QRjRhkVw.gif)

### Заключение

Подводя итог: программный подход даёт больше контроля над устройством и масштабируемостью приложения и позволяет разработчику сосредоточиться на программировании, а не полагаться только на storyboards. Особенно это касается проблем с IBAction/IBOutlet**. **Одна из проблем при рефакторинге кода с переменными IBOutlet и IBAction в том, что после изменений связи приходится восстанавливать заново. По моему опыту, через несколько дней работы с кодовой базой приложение начало неожиданно падать без какой-либо понятной причины. Разобравшись, я выяснил, что причиной падений были переименованные переменные IBOutlet и IBAction. Каждый раз, когда это происходило, мне приходилось вручную заново подключать затронутые переменные, чтобы всё снова заработало. Это отнимает время, раздражает и сбивает рабочий процесс.

Спасибо за чтение!

```

```

