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.tabBarContro
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 @[];
}
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....
I assume you have UINavigationController
s 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];