Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在此嵌套流中正确访问tabBarController?_Ios_Swift_Uiviewcontroller_Uinavigationcontroller_Uitabbarcontroller - Fatal编程技术网

Ios 如何在此嵌套流中正确访问tabBarController?

Ios 如何在此嵌套流中正确访问tabBarController?,ios,swift,uiviewcontroller,uinavigationcontroller,uitabbarcontroller,Ios,Swift,Uiviewcontroller,Uinavigationcontroller,Uitabbarcontroller,我有一个UINavigationController作为rootViewController,它最终将UITabBarController推到堆栈的顶部 UITabBarController有两页。每个页面都有UINavigationController作为根,假设这是UINavigationControllerA和B A和B都有一个UIViewController作为根。假设这是C和D 现在我正在处理类UIViewControllerC。我想从C获取对uitabarcontroller的引用。

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

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

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

现在我正在处理类
UIViewController
C。我想从C获取对
uitabarcontroller
的引用。因此我执行以下操作:

  • self.tabBarController
  • self.navigationController?.tabBarController

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

根据我的经验,对于这种层次结构,只需换一种方式,从顶部开始

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

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 var ownerTabBarController: MyTabBarViewController?
我们可以做到:

ownerTabBarController?.executeSomeMethod()

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

您试图在视图控制器中的何处访问选项卡控制器?如果在正确的位置调用,两次尝试都应该有效。将代码张贴在要添加控制器C的位置UITabBarController@rmaddy是的,从我在网上看到的,应该是,但令人惊讶的是,这两个代码我都得到了零。@iraniyaneyansh我使用故事板将
UINavigationControllers
UIViewControllers
放入
uitabarcontroller
@ChenLiYong你没有回答我的问题。代码在哪里?