Adding buttons to the titleview of NavigationBar without having to repeat code

Go To


To give some background, I am making a UINavigationControlled-based blog type app (I suppose it most closely resembles the iPhone facebook app). Regardless of the view that is currently active, the NavigationBar shows some buttons in its title area, such as Friend Requests and Activity Notifications. In much the same was as the facebook app, clicking these buttons will create a popup view.

Currently, I am doing things in a way that I feel is incredibly inefficient. For every view that is loaded, I am recreating the buttons and adding them to the navigation bar. My code is below:

//Setup the custom middle buttons
UIView *container = [[UIView alloc] init];
container.frame = CGRectMake(0, 0, 80, 44);

// create a button and add it to the container
UIButton *notificationButton = [UIButton buttonWithType:UIButtonTypeCustom];
notificationButton.frame = CGRectMake(0, 0, 35, 44);
[notificationButton addTarget:self 
[container addSubview:notificationButton];

// add another button to the container
UIButton *friendActivityButton = [UIButton buttonWithType:UIButtonTypeCustom];
friendActivityButton.frame = CGRectMake(45, 0, 35, 44);
[friendActivityButton addTarget:self 
[container addSubview:friendActivityButton];

// Set the titleView to the container view
[self.navigationItem setTitleView:container];
[container release];

Since my app has multiple views and the navigation bar is always visible, it seems silly to keep on recreating the buttons, adding them to a container view, then adding that view to the titleView of the navigation controller.

What would be a better way of achieving the same effect? I was looking into subclassing or creating a category for UINavigationBar and maybe adding in the container view code there. However, I did not know how to make the selectors work in these cases. I also wasnt sure how to get access to the titleView property with a UINavigationBar category.

Any help on this would be great! Thank you!

2012-04-04 03:25
by kurisukun


I'd recommend just putting the above code in a UIViewController category (or a UIViewController subclass if you can subclass all your view controllers from a single root). Then in viewDidAppear, just call the above code (or put that in the superclass's viewDidAppear). I think that subclassing UINavigationBar is going to be more trouble than it's worth.

If you really want to avoid recreating the buttons (probably no reason to do so, but if it's important to you for some reason), you can wire the buttons to some singleton object rather than pointing them at self. The singleton could either handle the response directly, forward the message to the active view controller, or post a notification that the active view controller could listen for.

2012-04-04 14:28
by Rob Napier
Thank you, such a simple solution. I knew I was going about it wrong - kurisukun 2012-04-05 02:01