【问题标题】:How to properly access tabBarController in this nested flow?如何在这个嵌套流中正确访问 tabBarController?
【发布时间】:2018-03-02 04:56:58
【问题描述】:

我有一个UINavigationController 作为rootViewController,它最终将UITabBarController 推到堆栈的顶部。

UITabBarController 有 2 页。每个页面都有UINavigationController作为根,假设这是UINavigationController A和B。

A 和 B 都有一个 UIViewController 作为根。假设这是 C 和 D。

现在我正在编写 UIViewController C 类。我想从 C 中获得对 UITabBarController 的引用。所以我这样做了:

  • self.tabBarController
  • self.navigationController?.tabBarController

所有这些都返回零。如何获取对UITabBarController 对象的引用?

【问题讨论】:

  • 您试图在视图控制器的哪个位置访问选项卡控制器?如果在正确的地方调用,你的两种尝试都应该有效。
  • 发布你将控制器 C 添加到 UITabBarController 的代码
  • @rmaddy 是的,从我在互联网上阅读的内容来看,应该是,但令人惊讶的是,我的两个代码都为零。
  • @IraniyaNaynesh 我使用故事板将UINavigationControllersUIViewControllers 放入UITabBarController
  • @ChenLiYong 你没有回答我的问题。这段代码在哪里?

标签: ios swift uiviewcontroller uinavigationcontroller uitabbarcontroller


【解决方案1】:

根据我对这种层次结构的经验,只需另辟蹊径,从顶部开始。

对于这样的架构,我假设您期望拥有一个始终位于顶部的视图控制器,在您的情况下是导航控制器。我会添加一些代码来支持“主实例”过程:

static var mainInstance: TopNavigationController!

func viewDidLoad() {
    // super...
    TopNavigationController.mainInstance = self
    // ...
}

现在通过它访问你的标签栏视图控制器可能不会那么混乱:

if let tabBarController = TopNavigationController.mainInstance.myTabBarViewController {
    // Do stuff
}

在您的情况下,我会更深入地在您的标签栏视图控制器上创建一个“当前实例”过程。这仍然假设只有一个实例将同时加载,但预计不会一直存在。差别不大:

static weak var currentInstance: MyTabBarViewController? // We want it weak so it is released if we navigate back from it

func viewDidLoad() {
    // super...
    MyTabBarViewController.currentInstance = self
    // ...
}

这些过程有点懒惰,但对许多解决方案都很有用,并且可以在深度链接等情况下为您节省大量时间。

但是,如果这是不可能的,并且您通常只需要访问这些元素(可以是多个控制器)而不使用静态属性,那么仍然宁愿将委托或具体类发送到管道中:

例如,如果标签栏视图控制器需要执行在层次结构中触发的某些操作,您可以简单地执行以下操作:

let controller = SomeController()
controller.ownerTabBarController = self
self.navigationControllerAtIndex(1).push(controller...

那么SomeController显然有一个weak属性:

weak var ownerTabBarController: MyTabBarViewController?

并且可以做到:

ownerTabBarController?.executeSomeMethod()

我希望这能给您一些关于如何更好地在视图控制器之间创建消息传递的想法。即使您以后更改层次结构(这很容易发生),这些过程中的任何一个都应该起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2023-03-11
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多