Jules
Jules

Reputation: 7766

Programmatically switch to another tab AND switch to the first view controller?

How do I programmatically switch to another tab and go to the first view in the navigation stack ?

I can switch to a different tab.

self.tabBarController.selectedIndex = 4;

However, I also need to switch the a different view controller in the navigation stack of that tab.

How do I do that?

As soon as I run the code above, it switches, but to the currently loaded view controller in the navigation stack.

My view controllers are loaded into 5 navigation controllers which are added to the tab bar in app delegate.

Upvotes: 0

Views: 2693

Answers (3)

meierjo
meierjo

Reputation: 106

Know this is an old one, but I was faced with a similar problem. I have 3 tabs in a tabViewController, each tab has a Navigation tree that can be drilled through. When a user switches tab, I need the rootviewcontroller of that tab presented. My solution was to add the following lines to those view controllers in the Navigation trees:

    -(void)viewWillDisappear:(BOOL)animated
    {
       [super viewWillDisappear:YES];
        DLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
       [self.tabBarController.viewControllers[self.tabBarController.selectedIndex] popToRootViewControllerAnimated:YES];

     }

If the user is in any of the views with the above code and switches tabs, the tab they left is popped to the root view, so when they come back everything is cool....

Upvotes: 0

David Hoerl
David Hoerl

Reputation: 41622

Assuming the rootViewController for the tab bar controller is a navigation controller, get a reference to it then pop to the view controller you want. You can even do this BEFORE you switch the tab.

EDIT: I keep forgetting I subclassed UINavigationController to prevent the default behavior of the tab bar controller telling the navigation controller to pop to its rootViewController when the tab is switched (this is the behavior when a person taps on a tab, not sure if it happens when its done programmatically.) This is the code I use:

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
{
    //NSLog(@"popToRootViewControllerAnimated");

    return @[];
}

Upvotes: 0

DrummerB
DrummerB

Reputation: 40201

I assume you have UINavigationControllers in your UITabBarController. If that's the case you can use popToRootViewControllerAnimated: to go to the first view controller.

int index = 4;
self.tabBarController.selectedIndex = index;
[self.tabBarController.viewControllers[index] popToRootViewControllerAnimated:NO];

Upvotes: 4

Related Questions