获取选定的索引标签栏控制器 Swift

Get selected index tabbar controller Swift

我正在尝试获取 tabbarController 的选定索引。

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

我收到此错误:'UITabBarController?' does not have a member named 'selectedIndex'

我是不是漏掉了什么?

application.tabBarController 是可选的,这意味着它可以是 nil。 如果您确定它永远不会 nil,请执行以下操作:

var selectedIndex = tabBarController!.selectedIndex

你应该试试这个:

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