How do I set the default tab for tab bar controller in swift

16,378

Solution 1

User Omkar responded above with the correct answer. I can successfully switch the first tab using the following viewDidAppear in ThirdViewController.swft

override func viewDidAppear(animated: Bool) {         
    self.tabBarController?.selectedIndex = 0     
}

Solution 2

I followed @Paolo Sangregorio way The code to do it as follows

in appdelegate find applicationDidBecomeActive function and add this lines

let tabBarController = self.window?.rootViewController as! UITabBarController
tabBarController.selectedIndex = 0

Solution 3

//Use viewWillAppear (instead of) viewDidAppear to prevent a screen flicker


var freshLaunch = true
override func viewWillAppear(animated: Bool) {
    if freshLaunch == true {
        freshLaunch = false
        self.tabBarController.selectedIndex = 2
    }
}
Share:
16,378
kauai
Author by

kauai

Updated on June 15, 2022

Comments

  • kauai
    kauai almost 2 years

    I'm new to Swift, and about a 5 out of 10 on the Objective-C knowledge scale..

    I created a basic three tab Swift application. Each tab has an associated swift class file, e.g. FirstViewController.swift , SecondViewController.swift, ThirdViewController.swift.

    When I select the third tab, I now open the application preference settings using a viewDidAppear function override in ThirdViewController.swift, e.g.:

    override func viewDidAppear(animated: Bool) {
        // open app preference s
        if let url = NSURL(string:UIApplicationOpenSettingsURLString) {
            UIApplication.sharedApplication().openURL(url)
        }
    }
    

    Though, prior to opening the preferences, I would like to set the active tab back to the first tab. How is this done elegantly in Swift.

    The following does not work:

    self.tabBarController.selectedIndex = 0
    

    As the UIViewController of the ThirdViewController class does not have a tabBarController.

    Brian.