2

我正在使用一个有 4 个标签的标签栏,我想将第二个标签设置为默认值。我写了以下代码:

self.tabBarController!.selectedIndex = 2

但我收到以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

还有一件事我可以隐藏 UIViewController 或 UITabBarController 如果是,那么如何?

4

2 回答 2

4

你应该在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
}
于 2015-06-17T08:38:51.967 回答
4

我使用了 Ozgur 的代码并为 Swift 3 更新了它,它运行良好:

    if window?.rootViewController as? UITabBarController != nil {
        let tabBarController = window!.rootViewController as! UITabBarController
        tabBarController.selectedIndex = 3 // Opens the 4th Tab
    }

我放弃了 else 语句,因为如果它不起作用,那是很明显的。

于 2016-12-08T17:01:30.893 回答