Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset UINavigationController to first controller when tab bar is clicked

My application has 3 tab bar items, each mapped to a separate view controller. My problem is the first controller is a UINavigation controller, and it drills-down about 3 levels deep. I don't have any problems with the navigation, but when I click on a different tab bar item and then when I return to the first tab bar item (the one with the UINav controller), I'd prefer it to reset back to the first controller in the nav sequence.

I read that you have to do something like:

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    [[self navigationController] popViewControllerAnimated:NO];
}

But I'm not sure where I should put this method. Who is the delegate for the tab bar controller? It's setup in AppDelegate... should it go in there?

Thanks.

like image 917
rpheath Avatar asked Nov 06 '10 20:11

rpheath


2 Answers

Sure, in your AppDelegate when you are creating the UITabBarController you can set the tab bar controller's delegate to be self (i.e. the AppDelegate). Then you can put the tabBar:didSelectItem: method in your AppDelegate and it should be called whenever the user taps a UITabBarItem. I would create an instance variable property in your AppDelegate and keep a reference to the UITabBarItem which is used for the Nav controller tab (Let's call it tabBarItemForNavControllerTab). You should also have a reference to the nav controller that lives in that first tab so that you can control it from the AppDelegate (Let's call it navControllerInFirstTab)

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if (item != self.tabBarItemForNavControllerTab) {
        [self.navControllerInFirstTab popToRootViewControllerAnimated:NO];
    }
}

You can use popToRootViewControllerAnimated: on the UINavigationController instead of popping each one off the stack individually.

like image 70
Kenny Wyland Avatar answered Nov 11 '22 21:11

Kenny Wyland


You need to set yourself as the delegate for the tabBar and implement – tabBar:didSelectItem: the you ask the navigation controller for its views [[self navigationController ] viewControllers] which returns an NSArray of UIViewControllers, then pop each view controller in the array until you get to the root view.

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITabBarDelegate_Protocol/Reference/Reference.html

like image 28
Mauricio Galindo Avatar answered Nov 11 '22 21:11

Mauricio Galindo