在appdelegate中呈现多个模态视图

时间:2012-07-31 20:53:57

标签: iphone modalviewcontroller uiapplicationdelegate

我想在应用程序收到的每个推送消息之后呈现一个modalviewcontroller:“应用程序:(UIApplication *)应用程序didReceiveRemoteNotification:(NSDictionary *)userInfo”

我给出了这样的viewcontroller:

ReleaseViewController *viewController = [[ReleaseViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self.window.rootViewController presentModalViewController:navController animated:YES];

所以当另一个push-message到来并且旧的ModalViewController仍然可见时,我想在旧的上呈现一个新的modalviewcontroller。但它不起作用。没有发生任何事情,控制台只是说(我认为这是iOS 6 Beta的调试信息):

Warning: Attempt to present <UINavigationController: 0x1dde6c30> on <UINavigationController: 0x1dd73c00> whose view is not in the window hierarchy!

我做错了什么?

PS:我不想解散旧的ViewController,我希望它们能够堆叠。

谢谢!

2 个答案:

答案 0 :(得分:11)

您可以获得视图控制器的顶部,然后从该顶视图控制器中显示一个新模态

- (UIViewController *)topViewController:(UIViewController *)rootViewController
{
    if (rootViewController.presentedViewController == nil) {
        return rootViewController;
    }

    if ([rootViewController.presentedViewController isMemberOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        return [self topViewController:lastViewController];
    }

    UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
    return [self topViewController:presentedViewController];
}

你可以用rootViewController调用这个方法是window的rootViewController

答案 1 :(得分:1)

Full Decent很接近,但有一些错误导致你在某些情况下返回错误的视图控制器。这是一个更正版本。

private func topViewController(rootViewController: UIViewController) -> UIViewController {
    var rootViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
    repeat {
        guard let presentedViewController = rootViewController.presentedViewController else {
            return rootViewController
        }

        if let navigationController = rootViewController.presentedViewController as? UINavigationController {
            rootViewController = navigationController.topViewController ?? navigationController

        } else {
            rootViewController = presentedViewController
        }
    } while true
}