skip to Main Content

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


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

    Login or Signup to reply.
  2. 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
    

    }

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search