Skip to content

Instantly share code, notes, and snippets.

@mariancerny
Created May 16, 2014 07:15
Show Gist options
  • Save mariancerny/a168aa4e7e61777e1037 to your computer and use it in GitHub Desktop.
Save mariancerny/a168aa4e7e61777e1037 to your computer and use it in GitHub Desktop.
Wrapper for a modal view controller that should be assigned to rootViewController of a new UIWindow, so that the modal view controller can be presented out of the application flow (based for example on an external event).
@protocol TransparentViewControllerDelegate;
@interface TransparentViewController : UIViewController
- (instancetype)initWithRootViewController:(UIViewController *)rootViewController;
@property (nonatomic, weak) id<TransparentViewControllerDelegate> delegate;
@end
@protocol TransparentViewControllerDelegate <NSObject>
- (void)transparentViewControllerDidDismissRootViewController:(TransparentViewController *)transparentViewController;
@end
@interface TransparentViewController ()
@property (nonatomic, strong) UIViewController *rootViewController;
@property (nonatomic) BOOL didAlreadyAppear;
@end
@implementation TransparentViewController
- (instancetype)initWithRootViewController:(UIViewController *)rootViewController
{
self = [super init];
if (self) {
_rootViewController = rootViewController;
}
return self;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (self.didAlreadyAppear) {
[self.view.window resignKeyWindow];
self.view.window.hidden = YES;
if ([self.delegate respondsToSelector:@selector(transparentViewControllerDidDismissRootViewController:)])
[self.delegate transparentViewControllerDidDismissRootViewController:self];
} else {
if (self.rootViewController)
[self presentViewController:self.rootViewController animated:YES completion:nil];
self.rootViewController = nil;
}
self.didAlreadyAppear = YES;
}
@end
@mariancerny
Copy link
Author

Usage is as follows:

- (void)presentMyModalViewController
{
    UIViewController *myViewController = ...

    TransparentViewController *transparentViewController =
            [[TransparentViewController alloc] initWithRootViewController:myViewController];
    transparentViewController.delegate = self;

    UIWindow *specialWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    specialWindow.rootViewController = transparentViewController;
    [specialWindow makeKeyAndVisible];

    self.specialWindow = specialWindow;
}

- (void)transparentViewControllerDidDismissRootViewController:
                                 (TransparentViewController *)transparentViewController
{
    self.specialWindow = nil;
}

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