Horhe Garcia
Horhe Garcia

Reputation: 902

Programatically switching tabs using selectedViewController property

I've used search already, haven't found an answer.

Trying to switch like this:

[self. tabBarController.selectedViewController OptionsViewContorller];

and like this:

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

but it doesn't work, i also tried and advice to change

self.tabBarController.selectedIndex

but it only changes at tab bar not a view.

Upvotes: 1

Views: 6264

Answers (5)

Johnyoat
Johnyoat

Reputation: 456

for swift 4+

you have to get reference to the tab before the view was presented

let tab = self.presentingViewController as! UITabBarController
self.dismiss(animated: true, completion:{ 
     tab.selectedIndex = 2
})

Upvotes: 0

sancho
sancho

Reputation: 443

If you want to switch from your UITabBarController class, you have to write this code in -viewDidAppear:animated:

[((UIViewController *) self.viewControllers[0]).tabBarController setSelectedIndex:1];

Hope this help.

Upvotes: 0

Tajen
Tajen

Reputation: 21

// this code i am using to switch to tabbar view controller 0, first view controller.

self.tabBarController.selectedIndex = 0;

UIViewController *controller = [self.tabBarController.viewControllers objectAtIndex:0];
if ([controller isKindOfClass:[UINavigationController class]]) {
    [((UINavigationController*)controller) popToRootViewControllerAnimated:false];
}

[self.navigationController popToRootViewControllerAnimated:true];

Upvotes: 2

Wubao Li
Wubao Li

Reputation: 1748

This should work.

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

Upvotes: 6

Damo
Damo

Reputation: 12890

// viewControllerIndex is an int describing the position of the viewController
// in the tab bar array index
[self.tabBarController setSelectedIndex:viewControllerIndex];

Upvotes: 0

Related Questions