1

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?

3 Answers 3

3

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

}

Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.