view raw
Oliver Spencer Oliver Spencer - 7 months ago 58
Swift Question

Programatically switching between tabs within Swift

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 impelement this.


If your window rootViewController is UITabbarController(which is in most cases) than you can select tabbar in didFinishLaunchingWithOptions

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    // Override point for customization after application launch.

    if self.window!.rootViewController as? UITabBarController != nil {
        var tababarController = self.window!.rootViewController as UITabBarController
        tababarController.selectedIndex = 1

    return true

It will open the tab which index given in selectedIndex.

If you do this in viewDidLoad of your firstViewController than you need to manage by flag or something else if you really want to display firstViewController or you want to display secondViewController if you are coming first time which is not clean.So best place to do this in didFinishLaunchingWithOptions or rootViewController custom class viewDidLoad