iosswiftuikituinavigationcontroller

Why pushed ViewController has navigation controller in UIKit?


I'm not using storyboard and setup sceneDelegate like this

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

        self.window = window
    }

In this codes, navigation controller isn't initialized. And, If I call navigation controller in A_ViewController like this:

print(self?.navigationController)

It prints "nil". And, Can't navigate to other ViewControllers.
It make sense because I didn't initialized navigation controller.

If edit sceneDelegate like this code:

let rootNavigationController = UINavigationController(rootViewController: vc)
window.rootViewController = rootNavigationController

And push other VC from A_ViewController, then
Pushed ViewController has it's own navigation controller

I didn't initialize pushed VC's navigationController. Why pushed VC has navigationController?


Solution

  • UINavigationController:

    A navigation controller is a container view controller that manages one or more child view controllers in a navigation interface

    So it's a group of view controllers instead of a single view controller. Whenever you push a new controller, the internal controllers array in UINavigationController will append a new element. And vice versa, with pop the controller will be removed from this array. You can assume it's likely a singleton navigator in a workflow until you present a new workflow (without a new UINavigationController).

    You can see this in the documentation. All these view controllers: Setting, General and Auto-Lock had the same UINavigationController instance, although it might be created once on the Setting screen.

    enter image description here