Two UINavigationItems?

55 views Asked by At

Could anyone explain why there are two navigationItems? When I log like below:

NSLog(@"%@", self.navigationItem);
NSLog(@"%@", self.navigationController.navigationItem);

I get two different instances of UINavigationItem:

<UINavigationItem: 0x7f85b06f5a20>
<UINavigationItem: 0x7f85b06ab640>

I have only created a UINavigationController programmatically once.

2

There are 2 answers

7
thelaws On BEST ANSWER

All UIViewControllers have a property navigationItem. Therefore, because UINavigationController is a subclass of UIViewController, it also has this property.

self.navigationItem will be the one presented when your controller is pushed. The documentation for navigationItem, it's clear about this property

This is a unique instance of UINavigationItem created to represent the view controller when it is pushed onto a navigation controller.

self.navigationController.navigationItem would be the item displayed if Apple allowed UINavigationControllers to be nested. However, since this isn't allowed, it's best to forget about it.

0
scott On

Okay, this question puzzled me for awhile but I think I figured it out. self.navigationItem and self.navigationController.navigationItem are two different objects. Here's why:

In iOS, each UIViewController object has a UINavigationItem. The navigationItem for your current view controller is self.navigationController, and self.navigationController.navigationItem is kind of a spillover object, it's the navigationItem for your parent navigationController.