获取iOS中顶级viewcontroller的参考

时间:2012-11-14 06:46:46

标签: ios

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

这看起来像是一个非常常见的用例,我觉得奇怪的是很难访问顶部|可见的视图控制器

4 个答案:

答案 0 :(得分:3)

这也应该遵循你的模态视图和导航控制器(如果有的话):

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

答案 1 :(得分:1)

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

但是现在我只是给你自己挂绳子的绳索:

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

答案 2 :(得分:0)

-(UIViewController *)getCurrentViewController
{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];

    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    return result;
}

答案 3 :(得分:0)

DateTime inDate;
string currentFormat = "MM/dd/yyyy";
DateTime.TryParseExact(empBirthDate, currentFormat , CultureInfo.InvariantCulture, DateTimeStyles.None, out inDate);
txtBirthDate.SelectedDate = inDate;