Programmatically switching between tabs within Swift Programmatically switching between tabs within Swift ios ios

Programmatically switching between tabs within Swift


If your window rootViewController is UITabbarController(which is in most cases) then you can access tabbar in didFinishLaunchingWithOptions in the AppDelegate file.

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {    // Override point for customization after application launch.    if let tabBarController = self.window!.rootViewController as? UITabBarController {        tabBarController.selectedIndex = 1    }    return true}

This will open the tab with the index given (1) in selectedIndex.

If you do this in viewDidLoad of your firstViewController, you need to manage by flag or another way to keep track of the selected tab. The best place to do this in didFinishLaunchingWithOptions of your AppDelegate file or rootViewController custom class viewDidLoad.


1.Create a new class which supers UITabBarController.E.g:

class xxx: UITabBarController {override func viewDidLoad() {        super.viewDidLoad()}

2.Add the following code to the function viewDidLoad():

self.selectedIndex = 1; //set the tab index you want to show here, start from 0

3.Go to storyboard, and set the Custom Class of your Tab Bar Controller to this new class.(MyVotes1 as the example in the pic)

enter image description here


Swift 3

You can add this code to the default view controller (index 0) in your tabBarController:

    override func viewWillAppear(_ animated: Bool) {        _ = self.tabBarController?.selectedIndex = 1    }

Upon load, this would automatically move the tab to the second item in the list, but also allow the user to manually go back to that view at any time.