Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading