我正在使用一个有 4 个标签的标签栏,我想将第二个标签设置为默认值。我写了以下代码:
self.tabBarController!.selectedIndex = 2
但我收到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
还有一件事我可以隐藏 UIViewController 或 UITabBarController 如果是,那么如何?
我正在使用一个有 4 个标签的标签栏,我想将第二个标签设置为默认值。我写了以下代码:
self.tabBarController!.selectedIndex = 2
但我收到以下错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
还有一件事我可以隐藏 UIViewController 或 UITabBarController 如果是,那么如何?
你应该在AppDelegate
课堂上didFinishLaunchingWithOptions
使用这样的方法
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
if self.window!.rootViewController as? UITabBarController != nil {
var tabbarController = self.window!.rootViewController as UITabBarController
tabbarController.selectedIndex = 2
}
else{
println("couldn't reach rootViewController named UITabBarController")
}
return true
}
我使用了 Ozgur 的代码并为 Swift 3 更新了它,它运行良好:
if window?.rootViewController as? UITabBarController != nil {
let tabBarController = window!.rootViewController as! UITabBarController
tabBarController.selectedIndex = 3 // Opens the 4th Tab
}
我放弃了 else 语句,因为如果它不起作用,那是很明显的。