I am using the following function via a notification to load a right button on my UINavigationBar, and even though I can trace out the button and verify it is allocated, it does not show up...any ideas?
EDIT 4/6/2011, 2:42PM
So, something interesting...the width always reports as 0.0...
- (void)showRightBarButton:(id)sender
{
NSLog(@"Showing button");
UIBarButtonItem *button = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(showPI:)];
[button setTitle:@"This Button"];
self.navigationItem.rightBarButtonItem = button;
//[[self.navigationItem rightBarButtonItem] setWidth:50];
NSLog(@"Button width is %f.", self.navigationItem.rightBarButtonItem.width);
[button release];
}
[self.view setNeedsDisplay];
You're right. That line isn't needed. As far as the rest of the code goes I don't see what's wrong with it. The only thing I've come up with so far is that self isn't the currently displayed view controller or that you're missing a navigation controller. Perhaps you've created your UINavigationBar
yourself instead of using a navigation controller?
Anyway, for easier debugging I would suggest the following:
- (void)showRightBarButton:(id)sender
{
NSLog(@"Showing button");
UIBarButtonItem *button = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(showPI:)];
self.navigationItem.rightBarButtonItem = button;
[button release];
}
EDIT: The width isn't interesting. It's always 0.0 unless you specify it yourself.
The problem is that you're adding the button in the wrong place. You're not supposed to add the button to the navigation item of the navigation controller, but to the navigation item of the controller that is currently displayed by the navigation controller.
You say you're using an NSNotification to trigger the addition of the bar button item. Where are you registering for the notification? Is it possible that the notification is being received before your view is loaded?
If you're registering for notifications in -init
you may want to set a flag on your view controller that you should be displaying the bar button item and then reference that flag in -viewDidLoad
to optionally display it.
Or you could just register for the notification in -viewDidLoad
.