Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 451
MLyck Avatar asked Mar 01 '15 12:03

MLyck


People also ask

How do I create a custom navigation bar in Swift?

Go to the ViewController. swift file and add the ViewDidAppear method. a nav helper variable which saves typing. the Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow.


2 Answers

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()
}
like image 185
Jogendra.Com Avatar answered Oct 12 '22 04:10

Jogendra.Com


Value of type 'AppDelegate' has no member 'window'

For those building newer projects with SceneDelegate.swift, you can use the 'var window: UIWindow?' in SceneDelegate instead of the removed 'var window' in AppDelegate

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 viewController = ViewController()
    let navViewController = UINavigationController(rootViewController: viewController)
    window?.rootViewController = navViewController
}
like image 23
candyline Avatar answered Oct 12 '22 04:10

candyline