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

时间:2015-02-09 22:23:53

标签: ios swift uitabbarcontroller selectedindex

我正在尝试获取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'

我错过了什么吗?

2 个答案:

答案 0 :(得分:12)

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

var selectedIndex = tabBarController!.selectedIndex

答案 1 :(得分:2)

你应该试试这个:

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