Skip to content

Instantly share code, notes, and snippets.

@MartinMoizard
Created September 12, 2013 13:37
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save MartinMoizard/6537467 to your computer and use it in GitHub Desktop.
Save MartinMoizard/6537467 to your computer and use it in GitHub Desktop.
Category on UIViewController: recursive function to present a modal View Controller anywhere in the application. Example: [self.window.rootViewController presentViewControllerFromVisibleViewController:myViewController]; Works with application using only UINavigationController and modal views. Can be enhanced to handle UITabBarController or other…
- (void)presentViewControllerFromVisibleViewController:(UIViewController *)viewControllerToPresent
{
if ([self isKindOfClass:[UINavigationController class]]) {
UINavigationController *navController = (UINavigationController *)self;
[navController.topViewController presentViewControllerFromVisibleViewController:viewControllerToPresent];
} else if (self.presentedViewController) {
[self.presentedViewController presentViewControllerFromVisibleViewController:viewControllerToPresent];
} else {
[self presentModalViewController:viewControllerToPresent animated:YES];
}
}
@anoop4real
Copy link

anoop4real commented Nov 29, 2016

Tried adding support for Tabbar, i tried using it for a subclass of tab bar.....but system couldnt recognize the selector "presentViewControllerFromVisibleViewController", category to viewcontroller is enough to support tabbar also right?

#import "UIViewController+PresentModal.h"

@implementation UIViewController (PresentModal)

- (void)presentViewControllerFromVisibleViewController:(UIViewController *)viewControllerToPresent
{
    if ([self isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabController = (UITabBarController *)self;
        [tabController.selectedViewController presentViewControllerFromVisibleViewController:viewControllerToPresent]
    }
    else if ([self isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navController = (UINavigationController *)self;
        [navController.topViewController presentViewControllerFromVisibleViewController:viewControllerToPresent];
    } else if (self.presentedViewController) {
        [self.presentedViewController presentViewControllerFromVisibleViewController:viewControllerToPresent];
    } else {
        [self presentModalViewController:viewControllerToPresent animated:YES];
    }
}
@end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment