以编程方式切换Swift中的选项卡

我需要编写一些代码,以便在iOS应用程序启动时将视图切换到另一个选项卡(例如,默认显示第二个选项卡,而不是第一个选项卡)。

我是新来的Swift,并已经制定了以下内容:

  • 代码可能应该在第一个选项卡的ViewController的覆盖func viewDidLoad()函数中进行。

  • 下面的代码显示了第二个ViewController,但不是底部的标签栏(vcOptions是第二个ViewController标签项:

let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("vcOptions") self.showViewController(vc as UIViewController, sender: vc) 

我想答案可能在于使用UITabbarController.selectedIndex = 1,但不太清楚如何实现这个。

如果您的window rootViewControllerUITabbarController (在大多数情况下),您可以selectdidFinishLaunchingWithOptions tabbar

 func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. if self.window!.rootViewController as? UITabBarController != nil { var tababarController = self.window!.rootViewController as UITabBarController tababarController.selectedIndex = 1 } return true } 

它将打开selectedIndex index给定index的选项卡。

如果你在你的firstViewController viewDidLoad中执行这个操作,比你需要用flag或者别的东西来pipe理,如果你真的想要显示firstViewController或者你想显示secondViewController如果你第一次来的时候不干净,那么最好的地方是didFinishLaunchingWithOptionsrootViewController自定义类viewDidLoad

1.创build一个超类UITabBarController的新类。 例如:

 class xxx: UITabBarController { override func viewDidLoad() { super.viewDidLoad() } 

2.将以下代码添加到函数viewDidLoad()中:

 self.selectedIndex = 1; //set the tab index you want to show here, start from 0 

3.转到故事板,将选项卡栏控制器的自定义类设置为这个新类。 (MyVotes1作为图片中的例子)

在这里输入图像说明

要扩展@codester的答案,你不需要检查然后分配,你可以一步完成:

 func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Override point for customization after application launch. if let tabBarController = self.window!.rootViewController as? UITabBarController { tabBarController.selectedIndex = 1 } return true } 

Swift 3

您可以将此代码添加到tabBarController中的默认视图控制器( index 0 ):

  override func viewWillAppear(_ animated: Bool) { _ = self.tabBarController?.selectedIndex = 1 } 

加载后,这会自动将选项卡移动到列表中的第二项,但也允许用户随时手动返回到该视图。