3

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

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Lenny1357
  • 748
  • 1
  • 13
  • 21

3 Answers3

3

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.

Leonardo
  • 1,740
  • 18
  • 27
  • _should_ sounds too strict to me here, @chandan reply is perfectly valid, the property even has a `setRightBarButtonItem` setter so is meant to be used by API design. – Jaime Agudo Dec 18 '16 at 15:10
1

In Objective-C

UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Flip"                                            
                               style:UIBarButtonItemStyleBordered 
                               target:self 
                               action:@selector(flipView:)];
nav1.navigationBar.navigationItem.rightBarButtonItem = flipButton;

In Swift

let barBtnVar = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(Nam1BarBtnKlkFnc(_:)))
self.navigationItem.setRightBarButtonItem(barBtnVar, animated: true)
Yaobin Then
  • 2,662
  • 1
  • 34
  • 54
Chandan
  • 747
  • 7
  • 17
0

Try this in your viewDidLoad's method:

    let label = UILabel(text: "Reminder")
    self.navigationController?.navigationBar.topItem?.titleView = label
Display Name
  • 4,502
  • 2
  • 47
  • 63