简体   繁体   中英

iOS - opposite of nil for rightBarButtonItem

I need to make a button reappear after I set it to nil but I can't seem to figure it out.

I set it to nil using:

self.navigationItem.rightBarButtonItem =nil;

When you set the button to nil you destroy (deallocate) it. Just recreate the button. Or, if it's expensive to create for some reason, create another property which holds the button and then use that to restore the rightBarButtonItem .

It's a requirement to set the button to nil? Another approach is to set the button's background alpha to 0, or disable it with setEnabled:NO. If it's a requirement, you have two options:

  • Store the button as a property and assign the button to the rightBarButtonItem of the navigationItem. Make sure you do all button manipulation to the property.

  • Create a method to create an instance of UINavigationItem with the button and assign this button to rightBarButtonItem. By the way, if you want to have exactly the same instance you had in the nil assignment, you must use the first option.

Hope it helps!

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(done)];
[self.navigationItem setRightBarButtonItem:doneButton animated:YES]

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];

Or create a property of the barbuttonitem and just pass it whenever you need it.

@property (nonatomic, retain) UIBarButtonItem *rightNavButton;
self.navigationItem.rightBarButtonItem = self.rightNavButton;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM