Bins Ich
Bins Ich

Reputation: 1842

iOS Tabbar - Change to first tab and first ViewController

I need some help regarding my Tabbar application.

Currently my Tabbar looks like the following:

Assume ViewController2 is the current displayed ViewController. Now I switch to ViewController3 and want to switch to ViewController1 programmatically.

The problem is, since the active ViewController in Tab1 is ViewController2

[self.tabBarController setSelectedIndex:0];

will always switch to ViewController2. But how can I switch to ViewController1 in that case?

This also doesn't work out for me:

self.tabBarController.selectedViewController
= [self.tabBarController.viewControllers objectAtIndex:0];

Would be glad fro some hints.

Upvotes: 3

Views: 3088

Answers (4)

fozoglu
fozoglu

Reputation: 829

Swift 3 version

 self.tabBarController?.selectedIndex = 0
 let navController = self.tabBarController?.selectedViewController as! UINavigationController
 navController.popToRootViewController(animated: true)

Upvotes: 0

FD_
FD_

Reputation: 12919

Use something like

UINavigationController *navController=(UINavigationController*)[self.tabBarController.viewControllers objectAtIndex:0];
[navController popToRootViewControllerAnimated:YES];

Hope this helps

Upvotes: 2

Ian L
Ian L

Reputation: 5601

After setting the selectedIndex in code, you can then pop back to the root view controller of the navigation stack:

self.tabBarController.selectedIndex = 0;
UINavigationController *navController = self.tabBarController.selectedViewController;
[navController popToRootViewControllerAnimated:NO];

Upvotes: 3

nicolasthenoz
nicolasthenoz

Reputation: 1852

You have to pop viewController2 from your navigation controller. Just do

[self.tabBarController setSelectedIndex:0];
[(UINavigationController*)[self.tabBarController.viewControllers objectAtIndex:0] popViewControllerAnimated:NO];

Upvotes: 3

Related Questions