【问题标题】:Switch TabBar Item from separate Navigation Controller从单独的导航控制器切换 TabBar 项
【发布时间】:2020-01-15 17:33:21
【问题描述】:

在我的应用程序中,我有 TabBar 控制器和导航控制器以及一个未相互连接的视图控制器。

我在我的应用程序中使用 TabBar 控制器作为根 vc,并将其他导航控制器用作滑入 TabBar 控制器顶部的侧菜单。为了制作菜单,我使用了这个 repo - SideMenu

问题:如何从我拥有的菜单中切换 TabBar 项?简单地在 MenuViewController 中调用 tabBarController?.selectedIndex = 1 什么都不做。

到目前为止我做了什么:

  • 作为一个临时的工作解决方案,我使用通知中心在我的 ViewController 中注册由 TabBar 控制器提供的选项卡切换,但我认为这不是一个好主意,因为我有 5 个 VC,而且只有一个其中我有切换标签的功能。
  • 通过 Storyboard ID 调用 TabBar 然后使用它也没有帮助。
  • 扩展 UITabBarController 类也没有帮助(可能做错了)

【问题讨论】:

  • 如果您投反对票,请解释原因。也许我的问题不清楚?
  • 分享一些代码。

标签: ios swift uitabbarcontroller uitabbar uitabbaritem


【解决方案1】:

在我的应用程序中,我有 MainTabBarController,它几乎总是 root。我使用静态变量来访问共享变量。

class MainTabBarController: UITabBarController, UITabBarControllerDelegate {
    // MARK: - Variables
    public static var shared: MainTabBarController? {
        set {
            UIApplication.shared.window.rootViewController = newValue
        }

        get {
            guard let mainTabBarController = UIApplication.shared.window.rootViewController as? MainTabBarController else { return nil }

            return mainTabBarController
        }
    }
}

所以我可以随时更改它。

MainTabBarController.shared?.selectedIndex = 0

在 MenuViewController 中调用 tabBarController?.selectedIndex = 1 什么都不做。

这不应该工作,因为你的层次结构。

【讨论】:

  • 感谢您的回答。您的解决方案对我不太有效,但让我走上了正确的道路。我想出了这个:if let tabBarController = appDelegate.window!.rootViewController as? UITabBarController { },它允许我在代码中的任何地方访问我的 TabBarController。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-24
  • 2021-05-14
  • 1970-01-01
  • 2013-03-12
相关资源
最近更新 更多