获取对当前堆栈上的控制器的引用

Stu*_*rtM 2 uiviewcontroller uiview ios uistoryboard

如何从一个控制器创建一个指针到另一个已经在堆栈中并由StoryBoard创建的控制器.

例如,我使用该方法instantiateViewControllerWithIdentifier将视图控制器加载到堆栈/屏幕上.

我知道这背后有另一个控制器,仍然加载名为InitialViewController(类).如何获得我知道的控制器的引用/指针.

如果我尝试从self/navigationController注销presentViewController或presentViewController,它们将返回null.NSLog(@"present:%@",self.navigationController.presentedViewController);

编辑 - 有关应用程序中视图控制器的更多信息

  1. 初始视图控制器已加载(ECSlidingViewController的子类)
  2. 取决于用户是否已登录

    加载欢迎视图控制器(这是一个包含欢迎/登录/注册的导航堆栈)加载了Home View Controller(以家庭VC为根的导航堆栈)

基本上,初始视图控制器具有topViewController的属性,该属性设置为Home(导航堆栈)或Welcome(导航堆栈).

初始视图控制器始终在当前显示器上(从未见过).

我如何引用它,或创建指向它的指针.例如,如果我在Login VC的imp文件中,如何控制/链接到初始视图控制器上的视图而不用alloc/init重新创建它?

Big*_*Dan 5

如果您正在使用UITabBarController,则可以通过以下方式获取对其子UIViewControllers的引用:

[myTabBarController objectAtIndex:index];
NSLog(@"Selected view controller class type: %@, selected index: %d", [myTabBarController selectedViewController], [myTabBarController selectedIndex]);
Run Code Online (Sandbox Code Playgroud)

无论是以编程方式还是通过IB(最左边的tab = index 0),基于零的索引方案都遵循选项卡的顺序进行设置.

因为你看起来正在搜索的UIViewController引用似乎是rootViewController(因为你命名它的方式;'InitialViewController'),你也可以在你的appDelegate中尝试这个.这将需要5秒钟:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary     *)launchOptions
{

    NSLog(@"self.window.rootViewController = %@", NSStringFromClass([self.window.rootViewController class]));

    UIViewController *myRootViewController = self.window.rootViewController;

}
Run Code Online (Sandbox Code Playgroud)

让我知道如果这样做的伎俩:)

无论您使用的是UITabBarController还是UINavigationController,我都确定其中一个是您的rootViewController.一旦你获得它的引用,其余的很容易:

InitialViewController* myInitialViewController;

for (UIViewController *vc in [myRootViewController childViewControllers]) {
    if([vc isKindOfClass:[InitialViewController class]]){
        //Store this reference in a local/global variable or a property, 
        //or simply perform some logic on the vc pointer if you don't need to store it.
        myInitialViewController = (InitialViewController *)vc; //Example & reminder to cast your reference
    }
}
Run Code Online (Sandbox Code Playgroud)

根据评论中发现的新细节进行编辑:

好的,在topViewController的viewDidLoad或viewWillAppear中运行此代码:

//You have to import this class in order to reference it
#import "MESHomeViewController.h"

//Global variable for storing the reference (you can make this a property if you'd like)
MESHomeViewController *myHomeVC;

int i = 0;
for (UIViewController *vc in [self.slidingViewController childViewControllers]) {
    NSLog(@"Current vc at index %d = %@", i, [vc class]);

    if ([vc isKindOfClass:[MESHomeViewController class]]) {

        NSLog(@"Found MESHomeViewController instance - [[self.slidingViewController childViewControllers] objectAtIndex:%d]", i);
        myHomeVC = vc;
        break;

    }
    i++;
}
Run Code Online (Sandbox Code Playgroud)

看看那里是否有你的参考.如果是,您的控制台将打印出HomeViewController的类名.