Search code examples
iosswiftuinavigationcontrolleruinavigationbaruinavigationitem

How to add a NavigationItem to a programmatically created UINavigationController


I am using this code to programmatically add an UINavigationController to an existing UIViewController:

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let nav1 = UINavigationController()
let mainView = ReminderController(nibName: nil, bundle: nil)
nav1.viewControllers = [mainView]
self.window!.rootViewController = nav1
self.window?.makeKeyAndVisible()

Now I want to add a title to the NavigationBar managed by the UINavigationController but mostly I get this error:

Cannot call pushNavigationItem:animated: directly on a UINavigationBar managed by a controller

The code I used:

let item = UINavigationItem(title: "Reminder")
nav1.navigationBar.pushNavigationItem(item, animated: false)

Any other method I tried gave me the same error. So how to add a title to that NavController?

The NavBar looks like this right now:

enter image description here


Solution

  • Your NavigationBar is managed by the NavigationController, so you can't push an Item directly to it. Instead you should set the navigationItem on mainView and the NavigationController will take care of pushing it to the bar

    Also, check out the documentation for UINavigationController, I think it can give you a better understanding of how a navigationController works.

    This is from it:

    A navigation controller builds the contents of the navigation bar dynamically using the navigation item objects (instances of the UINavigationItem class) associated with the view controllers on the navigation stack.