How do I hide/show the right button in the Navigation Bar

Lauren Quantrell picture Lauren Quantrell · Apr 8, 2011 · Viewed 68.3k times · Source

I need to hide the right button in the Navigation Bar, then unhide it after the user selects some options.

Unfortunately, the following doesn't work:

NO GOOD: self.navigationItem.rightBarButtonItem.hidden = YES;  // FOO CODE

Is there a way?

Answer

Matt J picture Matt J · Apr 8, 2011

Hide the button by setting the reference to nil, however if you want to restore it later, you'll need to hang onto a copy of it so you can reassign it.

UIBarButtonItem *oldButton = self.navigationItem.rightBarButtonItem;
[oldButton retain];
self.navigationItem.rightBarButtonItem = nil;

//... later
self.navigationItem.rightBarButtonItem = oldButton;
[oldButton release];

Personally, in my apps I make my nav buttons into @properties, so that I can trash & recreate them at will, so something like:

//mycontroller.h
UIBarButtonItem *rightNavButton;
@property (nonatomic, retain) UIBarButtonItem *rightNavButton;

//mycontroller.m
@synthesize rightNavButton;
- (UIBarButtonItem *)rightNavButton {
    if (!rightNavButton) {
        rightNavButton = [[UIBarButtonItem alloc] init];
        //configure the button here
    }
    return rightNavButton;
}

//later, in your code to show/hide the button:
self.navigationItem.rightBarButtonItem = self.rightNavButton;