Get Selected Swift Index Tab Controller

I am trying to get the selected tabbarController index.

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

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

Did I miss something?

+2
source share
2 answers

application.tabBarControlleris optional, which means it can be nil. If you are sure you will never nil, do the following:

var selectedIndex = tabBarController!.selectedIndex
+9
source

you should try the following:

let application = UIApplication.shared.delegate as! AppDelegate
let tabbarController = application.window?.rootViewController as! UITabBarController
let selectedIndex = tabbarController.selectedIndex
0
source

Source: https://habr.com/ru/post/1016162/


All Articles