将第二个标签设置为swift

时间:2015-06-17 08:36:26

标签: swift uitabbarcontroller uitabbar xcode4.6.3

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

self.tabBarController!.selectedIndex = 2

但是我收到了以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

2 个答案:

答案 0 :(得分:4)

我使用了Ozgur的代码并将其更新为Swift 3并且它完美运行:

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

我删除了else语句,因为它很明显,如果它不起作用。

答案 1 :(得分:3)

你应该在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
}