Is it possible to check inside ViewController class that it is presented as modal view controller?
Best way to check
if (self.navigationController.presentingViewController) {
NSLog(@"Model Present");
}
If you don't need to distinguish between full-screen modal views and non-modal views, which is the case in my project (I was dealing with a problem that only occurs with form sheets and page sheets), you can use the modalPresentationStyle property of UIViewController:
switch (self.modalPresentationStyle) {
case 0: NSLog(@"full screen, or not modal"); break;
case 1: NSLog(@"page sheet"); break;
case 2: NSLog(@"form sheet"); break;
}
Here's my modified version of @GabrielePetronella's isModal, which works with contained view controllers in that it walks up the parentViewController hierarchy first. Also pulled the code out into multiple lines so it's clear what it's doing.
var isModal: Bool {
// If we are a child view controller, we need to check our parent's presentation
// rather than our own. So walk up the chain until we don't see any parentViewControllers
var potentiallyPresentedViewController : UIViewController = self
while (potentiallyPresentedViewController.parentViewController != nil) {
potentiallyPresentedViewController = potentiallyPresentedViewController.parentViewController!
}
if self.presentingViewController?.presentedViewController == potentiallyPresentedViewController {
return true
}
if let navigationController = potentiallyPresentedViewController.navigationController {
if navigationController.presentingViewController?.presentedViewController == navigationController {
return true
}
}
return potentiallyPresentedViewController.tabBarController?.presentingViewController is UITabBarController
}
A hack like this might work.
UIViewController* child = self;
UIViewController* parent = child.parentViewController;
while (parent && parent.modalViewController != child) {
child = parent;
parent = child.parentViewController;
}
if (parent) {
// A view controller in the hierarchy was presented as a modal view controller
}
However, I think my previous answer is a cleaner solution.
This should work.
if(self.parentViewController.modalViewController == self)…
What worked for me is following:
// this is the trick: set parent view controller as application's window root view controller
UIApplication.sharedApplication.delegate.window.rootViewController = viewController;
// assert no modal view is presented
XCTAssertNil(viewController.presentedViewController);
// simulate button tap which shows modal view controller
[viewController.deleteButton sendActionsForControlEvents:UIControlEventTouchUpInside];
// assert that modal view controller is presented
XCTAssertEqualObjects(viewController.presentedViewController.class, MyModalViewController.class);
As far as I tested it, this works for iOS7 and iOS8. Didn't try on iOS6 however.