根视图控制器的视图不在窗口层次结构中

时间:2015-12-31 00:21:39

标签: ios objective-c model-view-controller uiview-hierarchy

我编写了一个登录页面,在我的app委托中(在方法应用程序下:didFinishLaunchingWithOptions :)被设置为我的根视图控制器

[self.window setRootViewController:vc];

其中vc是我的HomeVC的实例。
此视图正确加载。我可以输入登录所需的所有数据,但是一旦我尝试加载另一个视图,我就会

Warning: Attempt to present <RegisterVC: 0x7d07f520> on 
         <HomeVC: 0x7d374830> whose view is not in the window hierarchy!

我尝试了一点点黑客,以确定我使用以下代码获得了最顶级的视图控制器:

- (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

但是,正如我所怀疑的那样,它只返回了当前的视图控制器,它也是根视图控制器。它甚至从未进入while循环。

我无法理解我正在尝试调用的视图控制器不仅在层次结构上时,它不仅显示正确,而且还是层次结构上仅视图。

编辑1:我将包括AppDelegate应用程序:didFinishLaunchingWithOptions:方法的部分,我创建并添加VC和导航VC。

    UIViewController *vc = (HomeVC *)[[HomeVC alloc] initWithNibName:NSStringFromClass([HomeVC class]) bundle:nil];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:vc];
    [self.navigationController setNavigationBarHidden:YES];

    [self.window setRootViewController:vc];
    //^^^This is the line I'm most suspicious of, is that correct?^^^
    [self.window setBackgroundColor:[UIColor colorWithHexString:kDefaultBackgroundColor]];
    [self.window makeKeyAndVisible];

1 个答案:

答案 0 :(得分:0)

你可以得到窗口的根视图控制器,它应该是导航控制器,然后得到它的顶视图控制器。

尝试这样:如果你确定有一个viewController.presentedViewController,那么发送includeModal为YES。

- (UIViewController *)topmostViewControllerFrom:(UIViewController *)viewController
                               includeModal:(BOOL)includeModal
{
    if ([viewController respondsToSelector:@selector(selectedViewController)])
    return [self topmostViewControllerFrom:[(id)viewController selectedViewController]
                              includeModal:includeModal];

    if (includeModal && viewController.presentedViewController)
    return [self topmostViewControllerFrom:viewController.presentedViewController
                              includeModal:includeModal];

    if ([viewController respondsToSelector:@selector(topViewController)])
    return [self topmostViewControllerFrom:[(id)viewController topViewController]
                              includeModal:includeModal];

    return viewController;
}