sarah sarah - 1 year ago 123
Objective-C Question

why there is a navigationItem in the UIViewController?

I am reading about UINavigation controller, and it makes sense to have a navigationItem in the NavigationController,

but when I create a UIViewController, there is also a property called navigationItem from type UINavigationItem

so now I have :

  1. navigationItem in the UIViewController

  2. navigationItem in the UINavigationController

do they have different purposes ?

It sounds like the navigationItem in the UINavigationController is not working because I did this code in a UIViewController:

self.navigationController!.navigationItem.title = "test2"

and the title didn't change, while I did this code:

self.navigationItem.title = "test"

and the title changed

Answer Source

The point is that all UIViewControllers have a UINavigationItem.

A UINavigationController decides what to show in its navigationBar by looking at the current viewController's navigationItem.

So you get this;

vcA.navigationItem.title = "A"
vcB.navigationItem.title = "B"

navigationController = UINavigationController(rootViewController: vcA)
// The title in the navigationBar is now "A"

navigationController.pushViewController(vcB, animated: true)
// The title in the navigationBar is now "B"

Since UINavigationController is also a subclass of UIViewController, it inherits the navigationItem as well, even though it's useless in most cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download