获取选定的索引tabbar控制器Swift

问题描述:

我想获取tabbarController的选定索引。获取选定的索引tabbar控制器Swift

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