将第二个选项卡设置为 swift 中的默认选项卡

问题描述 投票:0回答:3

我使用的选项卡栏有 4 个选项卡,我想将第二个选项卡设置为默认选项卡。我写了以下代码:

self.tabBarController!.selectedIndex = 2

但是我收到以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

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

swift uitabbarcontroller uitabbar xcode4.6.3
3个回答
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
}

4
投票

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

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

我删除了 else 语句,因为如果它不起作用,那是非常明显的。


0
投票

Swift 5 解决方案

在 TabBar 控制器类中。

class MyTabBarController: UITabBarController {
  
    override func viewDidLoad() {
      super.viewDidLoad()
      self.selectedIndex = 2  // Opens the 3rd Tab
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.