Set the second tab as default tab in swift

3.1k views Asked by At

I am using a tab bar which has 4 tabs and I want to set the second tab as default. I wrote the following code:

self.tabBarController!.selectedIndex = 2

But I got the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

And one more thing can I hide a UIViewController or UITabBarController if yes then how?

3

There are 3 answers

4
Özgür Ersil On

you should do it in AppDelegate class on didFinishLaunchingWithOptions method like that

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {

    if self.window!.rootViewController as? UITabBarController != nil {
        var tabbarController = self.window!.rootViewController as UITabBarController
        tabbarController.selectedIndex = 2
    }
    else{
        println("couldn't reach rootViewController named UITabBarController")
    }
    return true
}
0
Jack Ngai On

I used Ozgur's code and updated it for Swift 3 and it works perfectly:

    if window?.rootViewController as? UITabBarController != nil {
        let tabBarController = window!.rootViewController as! UITabBarController
        tabBarController.selectedIndex = 3 // Opens the 4th Tab
    }

I dropped the else statement as it is pretty obvious if it is not working.

0
Sajid Zeb On

Swift 5 Solution

Inside your TabBar Controller class.

class MyTabBarController: UITabBarController {
  
    override func viewDidLoad() {
      super.viewDidLoad()
      self.selectedIndex = 2  // Opens the 3rd Tab
    }

}