简体   繁体   中英

Difference between self.navigationController.navigationItem and self.navigationItem

What is the difference between self.navigationController.navigationItem and self.navigationItem? I am using a UINavigationController throughout the app and when I use self.navigationController.navigationItem.rightBarButtonItems, in one of the viewDidLoad methods of one of the viewControllers, the array is empty. However if I use self.navigationItem.rightBarButtonItems, I see my bar button items. What is the difference between the two calls? Thanks!

A UINavigationController is a subclass of UIViewController . As such, it has its own independent navigationItem property, which it inherited from UIViewController . You should ignore this property, as it would only be used if you were to embed a navigation controller inside another navigation controller (which nobody in their right mind would ever do).

From the documentation of UIViewController+UINavigationControllerItem , see below, we should be using the navigationItem property directly on the view controller:

// Created on-demand so that a view controller may customize its navigation appearance.
@property(nonatomic,readonly,strong) UINavigationItem *navigationItem;

UINavigationController also has a navigationItem property since it's inheriting from UIViewController , but setting it won't affect the view controller's navigation properties.

From a quick test, we can see that these navigation items are not equal either:

(lldb) po self.navigationItem
<UINavigationItem: 0x7f865c99ec50>

(lldb) expr -- @import UIKit
(lldb) po self.navigationController.navigationItem
<UINavigationItem: 0x7f865c811740>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM