获取对iOS中top viewcontroller的引用

获取对iOS中top viewcontroller的引用,ios,Ios,如何在我的应用程序中获取对顶部可见视图控制器的引用。我看到了一些利用navigationcontroller.[top | visible]viewcontroller的解决方案。但我的应用程序中不使用导航控制器 这似乎是一个非常常见的用例,我发现很奇怪,很难访问top | visible view controller您可能应该在这里使用委托模式,为子视图控制器提供一个可以调用的对象的引用。如果您编辑您的帖子来解释为什么您认为您需要对俯视图控制器的引用,我们可以为您提供有关如何在您的情况下使用

如何在我的应用程序中获取对顶部可见视图控制器的引用。我看到了一些利用navigationcontroller.[top | visible]viewcontroller的解决方案。但我的应用程序中不使用导航控制器


这似乎是一个非常常见的用例,我发现很奇怪,很难访问top | visible view controller

您可能应该在这里使用委托模式,为子视图控制器提供一个可以调用的对象的引用。如果您编辑您的帖子来解释为什么您认为您需要对俯视图控制器的引用,我们可以为您提供有关如何在您的情况下使用委托模式的建议

但现在我只给你一根绳子,你需要吊死自己:

UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;

您可能应该在这里使用委托模式,为子视图控制器提供对其可以调用的对象的引用。如果您编辑您的帖子来解释为什么您认为您需要对俯视图控制器的引用,我们可以为您提供有关如何在您的情况下使用委托模式的建议

但现在我只给你一根绳子,你需要吊死自己:

UIViewController *topVC = [UIApplication sharedApplication].keyWindow.rootViewController;

还应遵循模态视图和导航控制器(如果有):

- (UIViewController *)deepestPresentedViewControllerOf:(UIViewController *)viewController
{
    if (viewController.presentedViewController) {
        return [self deepestPresentedViewControllerOf:viewController.presentedViewController];
    } else {
        return viewController;
    }
}

- (UIViewController *)topViewController
{
    UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    UIViewController *deepestPresentedViewController = [self deepestPresentedViewControllerOf:rootViewController];
    if ([deepestPresentedViewController isKindOfClass:[UINavigationController class]]) {
        return ((UINavigationController *)deepestPresentedViewController).topViewController;
    } else {
        return deepestPresentedViewController;
    }
}

还应遵循模态视图和导航控制器(如果有):

- (UIViewController *)deepestPresentedViewControllerOf:(UIViewController *)viewController
{
    if (viewController.presentedViewController) {
        return [self deepestPresentedViewControllerOf:viewController.presentedViewController];
    } else {
        return viewController;
    }
}

- (UIViewController *)topViewController
{
    UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
    UIViewController *deepestPresentedViewController = [self deepestPresentedViewControllerOf:rootViewController];
    if ([deepestPresentedViewController isKindOfClass:[UINavigationController class]]) {
        return ((UINavigationController *)deepestPresentedViewController).topViewController;
    } else {
        return deepestPresentedViewController;
    }
}

那么你在你的案例中使用了什么?那么你在你的案例中使用了什么?你又在回答同样的问题了?如果你认为你找到了更好的解决方案,你可以考虑删除旧的帖子。谢谢,你又在回答同样的问题了?如果你认为你找到了更好的解决方案,你可以考虑删除旧的帖子。谢谢