5

I'm trying to get the selected index of the tabbarController.

let application = UIApplication.sharedApplication().delegate as AppDelegate
let tabbarController = application.tabBarController as UITabBarController
let selectedIndex = tabBarController.selectedIndex

I'm getting this error: 'UITabBarController?' does not have a member named 'selectedIndex'

Am I missing something?

2 Answers 2

14

application.tabBarController is an optional, this means it can be nil. If you are sure it will never be nil, do this:

var selectedIndex = tabBarController!.selectedIndex
4

you should try this:

let application = UIApplication.shared.delegate as! AppDelegate
let tabbarController = application.window?.rootViewController as! UITabBarController
let selectedIndex = tabbarController.selectedIndex
1
  • what about if the TabbarController is not the RootViewController ?
    – Houcine
    Commented Dec 21, 2019 at 18:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.