Search code examples
iosswiftuinavigationcontroller

Creating a navigationController programmatically (Swift)


I've been trying to redo the work on my app programmatically. (Without the use of storyboards)

I'm almost done, except making the navigation controller manually.

Currently, I only have 1 viewcontroller. And of course the appDelegate

The navigation Controller, will be used throughout all pages in the application.

If anyone could help me out, or send a link to some proper documentation for doing this programmatically it would be greatly appreciated.

EDIT:

I forgot to mention it's in Swift.


Solution

  • In AppDelegate.swift

    Swift 1, 2:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
       self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
       var nav1 = UINavigationController()
       var mainView = ViewController(nibName: nil, bundle: nil) //ViewController = Name of your controller
       nav1.viewControllers = [mainView]
       self.window!.rootViewController = nav1
       self.window?.makeKeyAndVisible()
    }
    

    Swift 4+: and Swift 5+

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
       self.window = UIWindow(frame: UIScreen.main.bounds)
       let nav1 = UINavigationController()
       let mainView = ViewController(nibName: nil, bundle: nil) //ViewController = Name of your controller
       nav1.viewControllers = [mainView]
       self.window!.rootViewController = nav1
       self.window?.makeKeyAndVisible()
    }