Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine whether a back button is displayed?

Tags:

ios

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.

like image 457
Josh Brown Avatar asked Oct 27 '11 17:10

Josh Brown


2 Answers

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.

like image 75
jrturton Avatar answered Oct 23 '22 15:10

jrturton


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

like image 26
Maximilian Litteral Avatar answered Oct 23 '22 16:10

Maximilian Litteral