ios 以编程方式在 Swift 中的选项卡之间切换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25325923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 01:50:30  来源:igfitidea点击:

Programmatically switching between tabs within Swift

iosxcodeswiftuitabbarcontrollerviewcontroller

提问by Oliver Spencer

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).

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

I'm new to Swift, and have worked out the following:

我是 Swift 的新手,并且已经解决了以下问题:

  • The code should probably go in the override func viewDidLoad() function of the ViewController of the first tab.

  • The following code shows the second ViewController, but not with the tab bar at the bottom (vcOptions is the second ViewController tab item:

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

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

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

I think the answer may lie in using the UITabbarController.selectedIndex = 1, but not quite sure how to implement this.

我认为答案可能在于使用 UITabbarController.selectedIndex = 1,但不太确定如何实现这一点。

回答by codester

If your windowrootViewControlleris UITabbarController(which is in most cases) then you can access tabbarin didFinishLaunchingWithOptionsin the AppDelegatefile.

如果您windowrootViewControllerUITabbarController(这是在大多数情况下),那么你可以访问tabbardidFinishLaunchingWithOptionsAppDelegate文件。

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
}

This will open the tab with the indexgiven (1) in selectedIndex.

这将打开带有index给定 (1)的选项卡selectedIndex

If you do this in viewDidLoadof 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 didFinishLaunchingWithOptionsof your AppDelegatefile or rootViewControllercustom class viewDidLoad.

如果您在viewDidLoad中执行此操作firstViewController,则需要通过标志或其他方式进行管理以跟踪所选选项卡。在didFinishLaunchingWithOptions您的AppDelegate文件或rootViewController自定义类中执行此操作的最佳位置 viewDidLoad

回答by WTIFS

1.Create a new class which supers UITabBarController. E.g:

1.创建一个新的类来取代UITabBarController。例如:

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

2.Add the following code to the function viewDidLoad():

2.在函数viewDidLoad()中加入如下代码:

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

3.Go to storyboard, and set the Custom Class of your Tab Bar Controller to this new class. (MyVotes1 as the example in the pic)

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

enter image description here

在此处输入图片说明

回答by Ponyboy

Swift 3

斯威夫特 3

You can add this code to the default view controller (index 0) in your tabBarController:

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

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

Upon load, this would automatically move the tab to the second item in the list, but also allow the user to manually go back to that view at any time.

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

回答by Anorak

To expand on @codester's answer, you don't need to check and then assign, you can do it in one step:

要扩展@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
}

回答by Leo Paim

The viewController has to be a child of UITabBarControllerDelegate. So you just need to add the following code on SWIFT 3

viewController 必须是UITabBarControllerDelegate的孩子。所以你只需要在SWIFT 3上添加以下代码

self.tabBarController?.selectedIndex = 1

回答by Pankaj Kulkarni

In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:

在一个典型的应用程序中有一个 UITabBarController 并且它嵌入了 3 个或更多 UIViewController 作为它的选项卡。在这种情况下,如果您将 UITabBarController 子类化为 YourTabBarController ,那么您可以简单地通过以下方式设置所选索引:

selectedIndex = 1 // Displays 2nd tab. The index starts from 0.

In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:

如果您从任何其他视图导航到 YourTabBarController,那么在该视图控制器的 prepare(for segue:) 方法中,您可以执行以下操作:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "SegueToYourTabBarController" {
            if let destVC = segue.destination as? YourTabBarController {
                destVC.selectedIndex = 0
            }
        }

I am using this way of setting tab with Xcode 10 and Swift 4.2.

我在 Xcode 10 和 Swift 4.2 中使用这种设置选项卡的方式。

回答by Rob D

Just to update, following iOS 13, we now have SceneDelegates. So one might choose to put the desired tab selection in SceneDelegate.swift as follows:

只是为了更新,在 iOS 13 之后,我们现在有了 SceneDelegates。因此,可以选择将所需的选项卡选择放在 SceneDelegate.swift 中,如下所示:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, 
               willConnectTo session: UISceneSession, 
               options connectionOptions: UIScene.ConnectionOptions) {

        guard let _ = (scene as? UIWindowScene) else { return }

        if let tabBarController = self.window!.rootViewController as? UITabBarController {
            tabBarController.selectedIndex = 1
        }

    }

回答by Shakeel Ahmed

Swift 5

斯威夫特 5

//MARK:- if you are in UITabBarController 
self.selectedIndex = 1

or

或者

tabBarController?.selectedIndex = 1