Programmatically switching between tabs within Swift

Oliver Spencer picture Oliver Spencer · Aug 15, 2014 · Viewed 105.8k times · Source

I need write some code to switch the view to another tab when the iOS app starts (so, for example, the second tab is shown by default rather than the first).

I'm new to Swift, and have worked out the following:

  • The code should probably go in the override func viewDidLoad() function of the ViewController of the first tab.

  • The following code shows the second ViewController, but not with the tab bar at the bottom (vcOptions is the second ViewController tab item:

let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("vcOptions")
self.showViewController(vc as UIViewController, sender: vc)

I think the answer may lie in using the UITabbarController.selectedIndex = 1, but not quite sure how to implement this.

Answer

codester picture codester · Aug 15, 2014

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.