[iOS] How to get top most view controller?

+ (UIViewController *)topViewController
{
    return [self topViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
}

+ (UIViewController *)topViewController:(UIViewController *)rootViewController
{
    if (rootViewController.presentedViewController == nil) {
        return rootViewController;
    }
    if ([rootViewController.presentedViewController isKindOfClass:[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];
}

+ (UINavigationController *)navigationController
{
    UIViewController *topViewController = [self topViewController];
    UINavigationController *navigationController = nil;
    if ([topViewController isKindOfClass:[UINavigationController class]])
    {
        navigationController = (UINavigationController *)topViewController;
    }else
    {
        navigationController = topViewController.navigationController;
    }

    return navigationController;
}

Comments

Popular posts from this blog

Play video inside OpenGL ES by using MediaCodec

Using AssetManager on native language JNI, C++

[iOS] Custom back button with back gesture