views:

303

answers:

3

Hi,

I am using my own custom navigationBar, but i need to access it in a number of different views because i need to add buttons, change title and so forth.

Should i pass a reference to my navigationBar each time i show a new view, or just make it a singleton so i can access it from any view?

A: 

Make it a global variable.

Eric Normand
i am reading things on the web that say its not best practice to use global vars, instead use singletons
Ton
I would avoid using a global variable if at all possible, as it eschews encapsulation. Say you need to do a modal view controller, which is going to have to have a similar navigation bar. Oops, now both navigation controllers are going to be trying to use the same navigation bar, which won't end up good.
Andrew Pouliot
+2  A: 

Are you using a UINavigationController? If so, you can access the navigation bar from any sub-controller like this:

UINavigationBar *bar = self.navigationController.navigationBar;
Justin Gallagher
+3  A: 

Neither.

You've listed adding buttons and changing titles as the reasons you need a custom toolbar, but both of those things can be done through the navigation controller with no need to create your own and therefore no need to create a singleton or a global variable.

When you push a new view controller, you can set the title for the navigation bar simply by calling [self setTitle:@"Nav Title"]; in the -viewDidLoad of that view controller. If you need to add a button, use code like the following (also in -viewDidLoad):

[[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
        initWithBarButtonSystemItem:UIBarButtonSystemItemEdit 
                             target:self 
                             action:@selector(setEditing)] autorelease]];

In other words, your design is flawed if you are creating a custom navigation bar only for the reasons you've listed. I suppose there are some good reasons to create a custom navigation bar, but these are not among them.

Consider reviewing the Configuring the Navigation Item Object section of the View Controller Programming Guide for iPhone OS.

Best regards,

Matt Long