Hubert Kunnemeyer
Hubert Kunnemeyer

Reputation: 2261

UINavigationController in a UITabBarController problems with view lifecycle

I'm experiencing some problematic behavior in my NavigationController. I have some UINavigationControllers in set up in my TabBarController(4 Tabs to be specific). MY AppDelegate conforms to the UITabBarControllerDelegate, which I use to trigger a popToRootViewController when the tab is switched, so when the user comes bak to that tab, it's back at the rootViewController. All works fine with this except: Upon "returning" to that Tab the viewWillAppear of the last viewController that was loaded gets called before loading the rootView's lifecycle. My Delegate implementation looks like the following;

#pragma -mark TabBarController
///////////////Pop our navigationControllers to the rootView when Tab is changed////////////////////////////////

- (void) tabBarController: (UITabBarController *) tabBarController didSelectViewController: (UIViewController *) viewController {

    if ([viewController isKindOfClass:[UINavigationController class]]) {
        NSLog(@"******POP TO ROOT VIEW*******");
       [(UINavigationController*)viewController popToRootViewControllerAnimated:NO];
    }

}

Now I realize the delegate method is didSelectViewController, but is there any way to prevent this behavior. Something that would be along the lines of did*Deselect*ViewController would be nice but that's not provided by the API. I really can't have the wrong viewWillAppear being called because I kick off a multi-threaded process there. Any suggestions?

Upvotes: 0

Views: 698

Answers (1)

danh
danh

Reputation: 62686

You can have the equivalent of a deselect by implementing shouldSelectViewController: and answering YES:

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {

    UIViewController *currentVC = tabBarController.selectedViewController;
    // whatever you would like to do on deselect, like
    [currentVC popToRootViewControllerAnimated:NO];
    // it will be at the root when you get back to it, and as a bonus, you have
    // a handle to viewController, which is about to be selected

    return YES;
}

Upvotes: 1

Related Questions