Yuuu
Yuuu

Reputation: 879

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?

Upvotes: 1

Views: 1932

Answers (3)

Visal Rajapakse
Visal Rajapakse

Reputation: 2042

Since you are using storyboard you should embed your ViewController in a Navigation controller. You can do that by,

  1. first opening your Main.storyboard file
  2. Select your initial ViewController
  3. Going into Editor > Embed in > Navigation Controller

or you could do it programmatically by refering @jignesh's answer

Upvotes: 0

jignesh
jignesh

Reputation: 129

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

}

Upvotes: 3

Shiraz Khan
Shiraz Khan

Reputation: 41

let viewController = FirstViewController()
let navVc = UINavigationController(rootViewController: viewController)
window?.rootViewController = navVc

You can not see your navigation bar because you are not embedding your current viewcontroller in to a navigation controller.

Upvotes: 0

Related Questions