问题描述
我需要编写一些代码,以便在iOS应用程序启动时将视图切换到另一个选项卡(例如,默认情况下显示第二个选项卡而不是第一个选项卡。)
I need write some code to switch the view to another tab when the iOS app starts (so, for example, the second tab is shown by default rather than the first).
我是Swift的新手,并且已经解决了以下问题:
I'm new to Swift, and have worked out the following:
-
代码可能应该放在覆盖第一个选项卡的ViewController的func viewDidLoad()函数。
The code should probably go in the override func viewDidLoad() function of the ViewController of the first tab.
以下代码显示第二个ViewController,但不显示底部的选项卡栏( vcOptions是第二个ViewController标签项:
The following code shows the second ViewController, but not with the tab bar at the bottom (vcOptions is the second ViewController tab item:
let vc : AnyObject! = self.storyboard.instantiateViewControllerWithIdentifier("vcOptions")
self.showViewController(vc as UIViewController, sender: vc)
我认为答案可能在于使用UITabbarController.selectedIndex = 1,但不太确定如何实现它。
I think the answer may lie in using the UITabbarController.selectedIndex = 1, but not quite sure how to implement this.
推荐答案
如果你的 window
rootViewController
是 UITabbarController
(在大多数情况下是这样)然后你可以在 AppDelegate
文件中的 didFinishLaunchingWithOptions
中访问 tabbar
。
If your window
rootViewController
is UITabbarController
(which is in most cases) then you can access tabbar
in didFinishLaunchingWithOptions
in the AppDelegate
file.
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
}
这将在 selectedIndex
中打开带有 index
给定(1)的标签。
This will open the tab with the index
given (1) in selectedIndex
.
如果你在你的 firstViewController viewDidLoad
中这样做>,您需要通过标记或其他方式进行管理以跟踪所选标签。在 didFinishLaunchingWithOptions
的 AppDelegate
文件或 rootViewController 自定义类
viewDidLoad
。
If you do this in
viewDidLoad
of your firstViewController
, you need to manage by flag or another way to keep track of the selected tab. The best place to do this in didFinishLaunchingWithOptions
of your AppDelegate
file or rootViewController
custom class viewDidLoad
.
这篇关于以编程方式在Swift中的选项卡之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!