Search code examples
iosxcodeuinavigationcontrollerpushback

Back button disappears after pushing two views using UINavigationController


I'm currently developing an app using a UINavigationController. I set the root view controller to ViewController1 and then push ViewController2 and then ViewController3 in response to button click events.

If I then click the back button from view 3, I'm returned to view 2 but this view has no back button. Interestingly as well, having set titles for each of these views ('View 1', 'View 2' and 'View 3' respectively), if I navigate from view 3 back to view 2 using the back button, the title changes to 'View 1' i.e. the title for the initial view (view 1) - not the title for view 2.

If anyone has any idea what might be going on here, your suggestions are very much appreciated.

Many thanks in advance!

Edit: I use the following code to init the UINavigationController in the app delegate:

self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen] bounds]];
self.viewController1 = [[ViewController1 alloc] init];
self.viewController2 = [[ViewController2 alloc] init];
self.viewController3 = [[ViewController3 alloc] init];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController1];
self.window.rootViewController = self.navigationController;

I later push view controllers to the UINavigationController on button clicks as follows:

MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
[self.navigationController pushViewController:appDelegate.viewController2 animated:YES];

Solution

  • I found the solution - in viewController2 and viewController3 I had the following code in order to hide the navigation bar (I wanted the navigation bar hidden on view1 and then visible on views 2 and 3).

    - (void) viewWillAppear:(BOOL)animated
    {
        [self.navigationController setNavigationBarHidden:NO animated:animated];
        [super viewWillAppear:animated];
    }
    
    - (void) viewWillDisappear:(BOOL)animated
    {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
        [super viewWillDisappear:animated];
    }
    

    I realised it makes far more sense to do the reverse in viewController1 i.e.

    - (void) viewWillAppear:(BOOL)animated
    {
        [self.navigationController setNavigationBarHidden:YES animated:animated];
        [super viewWillAppear:animated];
    }
    
    - (void) viewWillDisappear:(BOOL)animated
    {
        [self.navigationController setNavigationBarHidden:NO animated:animated];
        [super viewWillDisappear:animated];
    }
    

    and then removing the previous code from view controllers 2 and 3. This solved the issue.