2

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?

Amit Raj
  • 1,358
  • 3
  • 22
  • 47

2 Answers2

4

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
}
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
  • Thanks for quick response. I have used the above code in the didFinishLaunchingWithOptions method but app shows first tab as default tab. – Amit Raj Jun 17 '15 at 08:45
  • 1
    is your rootViewController named UITabBarController or different? Does it give any error?If it is not that means self.window!.rootViewController as? UITabBarController is nil and code block doesnt execute, you can see by writing else statement – Özgür Ersil Jun 17 '15 at 08:49
  • Yes, it goes to else part. What should I do now? – Amit Raj Jun 17 '15 at 09:25
  • This worked perfectly for me. I wanted to always start at tab[0] after the app had been in background. thank you – user462990 Jun 16 '19 at 12:19
4

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.

Jack Ngai
  • 157
  • 1
  • 9