尝试显示* on *,其视图不在窗口层次结构中

时间:2012-11-12 20:20:42

标签: objective-c ios cocoa-touch ios6

我正在尝试在我的app委托中创建一个模态视图控制器(我创建了一个名为showLoginView的函数)。但每当我尝试调用它时,我都会在XCode中收到警告:

Warning: Attempt to present <PSLoginViewController: 0x1fda2b40> on <PSViewController: 0x1fda0720> whose view is not in the window hierarchy!

以下是方法代码:

- (void)showLoginView
{
    PSLoginViewController *loginViewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:NULL] instantiateViewControllerWithIdentifier:@"PSLoginViewController"];
    [self.window.rootViewController presentViewController:loginViewController animated:NO completion:nil];
}

如何将视图添加到窗口层次结构中?或者我可能做错了什么?

7 个答案:

答案 0 :(得分:30)

您无法从appDelegate显示模态视图控制器。您需要从当前显示全屏的viewController中显示模态ViewController。换句话说,您需要将该代码放入根视图控制器中,或者您想要显示模态vc中的任何一个...

此外,您还需要使用方法“presentModalViewController”来呈现模态。您可以在模态vc上设置属性,例如:

vC.modalPresentationStyle = UIModalPresentationFormSheet;
vC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:vC animated:YES];

答案 1 :(得分:21)

只要您检测到当前可见的viewController并处理当前控制器是navigationController的情况,您实际上可以从AppDelegate呈现模态视图控制器。

以下是我的工作:

UIViewController *activeController = [UIApplication sharedApplication].keyWindow.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]]) {
   activeController = [(UINavigationController*) activeController visibleViewController];
}
[activeController presentModalViewController:loginViewController animated:YES];

答案 2 :(得分:8)

UIViewController *activeController = [UIApplication sharedApplication].keyWindow.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]])
{
   activeController = [(UINavigationController*) activeController visibleViewController];
}
else if (activeController.modalViewController)
{
    activeController = activeController.modalViewController;
}
[activeController presentModalViewController:vc animated:YES];

答案 3 :(得分:7)

我在iOS 7上遇到了这个问题 - 使任何提议的解决方案工作的关键是调用

[self.window makeKeyAndVisible];

AppDelegate中。 在那次通话之后,从窗口rootViewController提出模态视图。

答案 4 :(得分:6)

该警告的另一个原因可能是您想要从不是最顶层视图控制器的实例中呈现视图控制器。

首先,您必须获得最顶层的UIViewController并使用此实例来调用presentViewController:

UIViewController *root = [UIApplication sharedApplication].keyWindow.rootViewController;
while (root.presentedViewController) {
    root = root.presentedViewController;
}

答案 5 :(得分:3)

您可以使用NSLog(@“%@”,self.window.rootViewController),看看rootViewController到底是什么。

当rootViewController是普通的UIViewController时,我遇到了这个问题。 用UINavigationController替换它,希望它会有所帮助。

答案 6 :(得分:0)

在尝试从其他控制器的委托调用中呈现控制器时遇到此问题。 ie:显示带委托的搜索过滤器,一旦回到我的控制器并通过委托然后呈现控制器接收数据,我所要做的就是在代理中调度当前代码的原因,你在另一个线程中,那个& #39;为什么你要从主线程中向另一个线程中的另一个控制器呈现你的视图,所以必须回到主线程,只需将呈现的代码放在这样:

     dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:searchVC animated:true completion:nil];
 });

希望这有帮助!

相关问题