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
You can not see your navigation bar because you are not embedding your current viewcontroller in to a navigation controller.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
}
Since you are using storyboard you should embed your ViewController in a Navigation controller. You can do that by,
Main.storyboard
fileEditor > Embed in > Navigation Controller
or you could do it programmatically by refering @jignesh’s answer