In an iOS app, how can I determine whether a back button is displayed? Ideally, I'd like to know this in my controller's loadView
method.
Here's what I've tried in loadView
, viewDidLoad
, and viewWillAppear
:
if (self.navigationItem.backBarButtonItem)
and this:
if (self.navigationItem.leftBarButtonItem)
Neither of those work - they're always nil (the expression evaluates to false), even when there is a back button on the screen. What I'd ultimately like to do is set a Cancel button as the self.navigationItem.leftBarButtonItem
, but only if there's no back button. If there is a back button, we don't need the Cancel button. As it is, setting the leftBarButtonItem
is overriding the back button, so we're seeing a Cancel button all the time - even when there should be a back button.
You're asking the wrong object for its backBarButtonItem
. This property controls how an object is represented when it is the "back" item in the navigation stack.
Therefore, you need to be asking the view controller at the level below where you are in the navigation stack what its backBarButtonItem
is:
int n = [self.navigationController.viewControllers count] - 2;
if (n >= 0)
if ([(UIViewController*)[self.navigationController.viewControllers objectAtIndex:n]navigationItem].backBarButtonItem == nil)
// Do your thing....
You may need to check if the navigation controller has added your viewController to the stack at the time you are executing this code, the top view controller may still be the previous one. I've checked in viewWillAppear
and the stack does contain the new top controller at this point.
NSLog(@"%@",self.navigationController.navigationBar.backItem);
if (self.navigationController.navigationBar.backItem == NULL) {
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(addLaunch)];
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
}
this code works, its in the viewDidAppear, if your controller is null, theres no button, so i add the cancel button, its not a back item though, just a regular:] hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With