Question

I have an app that uses a side menu and has a few main screens that can be accessed from the menu and others that can only be accessed from these screens.

What I want is to have a menu button on the navigation bar that opens the menu and can only be visible on the main screens. On the other screens I want to have a back button, instead of the menu button.

I've already put the menu button like this:

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"IconMenu"] style:UIBarButtonItemStylePlain target:self.revealViewController action:@selector(revealToggle:)];

But I can't figure out how to change it with the back button when I need it.

Was it helpful?

Solution

Assuming than by "main screens" you mean root (first) view controllers in the navigation view controllers corresponding to the selected side menu items, this might be a solution for your problem: you can create a superclass for all your view controllers, say MyBaseViewController and rewrite viewWillAppear: method, that will determine whether it should have a default back button or a "revealSideMenu" button, based on whether it's a "main screen" or not.

 - (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self == [self.navigationController.viewControllers firstObject]) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage    imageNamed:@"IconMenu"] style:UIBarButtonItemStylePlain target:self.revealViewController action:@selector(revealToggle:)];
    }
}

OTHER TIPS

you can do that in 2 different ways:

the first is in the viewDidAppear check if the back button is already present (when you push a VC the back button automatically added but is avalaible programmatically only after the viewDidAppear) and then decide to add or not the menu button,

the second is add a parameter to your VC init method like isRoot or hasMenu or whatever you like to name it, and using that flag decide to add the menu or the back button

if you chose to add your own back button you have to call this method in your back selector

    [self.navigationController popViewControllerAnimated:YES];

The easiest way, IMO, is just to click on the title bar of the first ViewController and in the Attribute Inspector (⌥+⌘+4) change the Navigation Item info the way you want: Title -> what will show up in the back button* or if you want it to say something other than the Title of the first ViewController or the word "Back" you can just put it in the Back Button field.

*If the Title of the second ViewController is too long for it to fit it will be replaced with the word "Back" (and if the word "Back" doesn't fit it will only have the arrow sign).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top