Programatically switching tabs using selectedViewC

2020-07-27 05:48发布

问题:

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.

回答1:

This should work.

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


回答2:

// 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];


回答3:

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


回答4:

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.



回答5:

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
})