Search code examples
iosswiftxcodeuinavigationcontroller

Navigation bar is not displayed in Swift 5


I've been working on an iOS app and I'm trying to display a navigation bar to my app. I use a storyboard to just work on some basic UI, but for the other part like the navigation bar, I'm trying to implement it by code.

In the AppDelegate.swift file, I put the following code.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
    window = UIWindow(frame: UIScreen.main.bounds)
    UINavigationBar.appearance().tintColor = .black
    window?.rootViewController = FirstViewController()
    window?.rootViewController?.view.backgroundColor = UIColor.white
    window?.makeKeyAndVisible()
    return true
}

However, the navigation bar doesn't appear on FistViewController.

In the FirstViewController, I also put the following code into the viewwillappear function to display the navigation bar.

self.navigationController?.isNavigationBarHidden = false
self.navigationController?.navigationBar.barStyle = .black

As I said, I have a storyboard, but I only use it for setting FirstViewController as isInitialView controller. I also have a table view on the FirstViewController and I can see it, but I don't see the navigation bar.

So I was wondering if I make a mistake in writing code to display the navigation bar...

Does anyone know what I'm missing in here?


Solution

  • func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let viewController = FirstViewController()
    let navigationController = UINavigationController(rootViewController: viewController)
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()
    return true
    

    }