1
votes

I wonder if it's possible to add a button directly into a navigation controller, or I have to add button from all viewController pushed into navigation Controller?

Example: I have 3 UIViewController (VC1, VC2 and VC3) and I can push this elements in a NavigationController (NC). If I need to add a button as right navigation item for VC1 I can write in viewDidLoad of VC1 :

UIBarButtonItem *settingsBtn = [[UIBarButtonItem alloc]initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered target:self action:@selector(settings)];
self.navigationItem.rightBarButtonItem = settingsBtn;

If I need this button on NC also for VC2 and VC3 I have to add this code in VC2 and VC3 too and specify method "settings" in VC1,VC2 and VC3

Is it possible to add this button in a shared way? And how can I define settings method as shared method ?

2

2 Answers

1
votes

One way to do this is to have a parent class that your UIViewControllers derive from. In the parent class, you can set the button in, say, viewDidLoad. In your children classes, you would do [super viewDidLoad]; in your viewDidLoad method.

Hope this helps!

1
votes

Become a delegate of the UINavigationController.

- (void)navigationController:(UINavigationController *)navigationController
      willShowViewController:(UIViewController *)viewController
                    animated:(BOOL)animated {
UIBarButtonItem *settingsBtn = [[UIBarButtonItem alloc]initWithTitle:@"Settings"
                                                               style:UIBarButtonItemStyleBordered
                                                              target:self
                                                              action:@selector(settings)];
viewController.navigationItem.rightBarButtonItem = settingsBtn;
}