Creating a navigationController programmatically (Swift)

MLyck picture MLyck · Mar 1, 2015 · Viewed 91.4k times · Source

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.

I've been doing some research but I can't find any documentation of implementing this manually. (I started making the app as a Single View Application)

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.

Answer

Jogendra.Com picture Jogendra.Com · Mar 2, 2015

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