present more than one modalview in appdelegate

不问归期 提交于 2019-12-03 07:32:31

You can get top of your view controllers, then present a new modal from that top view controller

- (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];
}

You can call this method with rootViewController is window's rootViewController

Full Decent was close, but had a few mistakes that cause you to return the wrong view controller in some cases. Here is a corrected version.

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
}

Here is the same as above, but written in Swift

private func topViewController() -> UIViewController {
    var rootViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
    repeat {
        if rootViewController.presentingViewController == nil {
            return rootViewController
        }
        if let navigationController = rootViewController.presentedViewController as? UINavigationController {
            rootViewController = navigationController.viewControllers.last!
        }
        rootViewController = rootViewController.presentedViewController!
    } while true
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!