1
votes

I've a UIViewController which loads it's view form a Xib file. In my AppDelegate.m I would like to initiate my rootViewController with that myViewController and I would like that the title of the navigtionItem is set by taking the NavigationBar view which is part of the Xib file of the myViewController:

MyViewController *myViewController = [[MyViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:myViewController];

According to the documentation

Each time the top-level view controller changes, the navigation controller updates the navigation bar accordingly.

In my setup this seems not to happen or I haven't indicated that my NavigationBar view is actually the navigationBar to consider.

How can I tell the NavigationController to update it's navigationItem content (title, left and right bar buttons) according the NavigationBar view which is part of the Xib file from myViewController?

Update

My Xib layout looks like this:

Xib layout

I know I can set those items in code by:

self.navigationItem.titleView = ...;
self.navigationItem.leftBarButtonItem = ...;

But I want them do design in the Xib file of the ViewController and they should be used in the NavigationController.

2
Generally, I would assign self.navigationItem.titleView, self.navigationItem.leftBarButtonItem, etc., in the view controller's viewDidLoad method. - Chris Loonam
Did you add a NavigationBar view to the UIView in the xib? If so, that is not how it works. You need to actually add UINavigationItem to the controller in the xib. And then you also need to initialise the controller with the nib of course. - Rengers
@ ChrisLoonam thanks for the hint. This isn't was I'm looking for. See my update. @Rengers yes that's what I did and I want. I added UINavigationItem within the NavigationBar. See updated question. - Bruno Bieri

2 Answers

2
votes

In ViewWillAppear method in your ViewController set-

      self.navigationItem.title = @"Title name";

Also in the same way you can set self.navigationItem.leftBarButton and RightBarButton items

1
votes

Adding a UINavigationBar view to the main UIView doesn't do what you think it does. It merely adds a navigation bar view there in the view, it does not tie into the UINavigationController.

If you use a storyboard, you can add the UINavigationItem as a child of the UIViewController. But since you are not using a storyboard, the easiest way to do it is to update the navigationItem in viewDidLoad.


Sidenote: Apple does not recommend using viewDidLoad to setup the navigation item. If you really want to do it the proper way, you can for example do it in the navigationItem getter.

- (UINavigationItem*)navigationItem
{
  // get super navigation item
  UINavigationItem *navItem = [super navigationItem];

  // do stuff 

  return navItem;
}