Search code examples
iosuinavigationbarback-button

iOS Navigation Bar: change left bar button from menu to back


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.


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:)];
        }
    }