简体   繁体   中英

How can I determine whether a back button is displayed?

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

Search for the following

self.navigationController.navigationBar.backItem

instead of backBarButtonItem .

If backItem exists then you are on navigation stack further than rootViewController.

Just use this code:

if (![[[self.parentViewController childViewControllers] firstObject] isKindOfClass:[self class]]) {

}

loadView is too early. The earliest you could check this is in viewDidLoad . You may need to wait for viewWillAppear .

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