How can I present a modal view controller from the app delegate's view, the top most? Trying to present a modal view controller from a UIView, which made me confused.
Use your rootViewController
. You can present a modal view controller from any view controller subclass. If your root VC is a UITabBarController, then you can do:
[self.tabBarController presentModalViewControllerAnimated:YES]
or if its a navigation controller:
[self.navigationController presentModalViewControllerAnimated:YES]
etc.
EDIT: MVC
By trying to present a controller from within a view you are breaking the MVC pattern. Generally, a view is concerned with its appearance and exposing interfaces to communicate user interface state to its controller. For example, if you have a UIButton
in your view and you want it to present a modal view controller, you don't hard wire the view to do this. Instead, when a controller instantiates the view, the controller configures the button by setting itself as a target to receive the touchUpInside
action where it can present the appropriate modal view controller.
The view itself does not (and should not) have this contextual knowledge to do the work of a controller.
The best way to do this is to create a new UIWindow
, set it's windowLevel
property, and present your UIViewController
in that window.
This is how UIAlertView
s work.
Interface
@interface MyAppDelegate : NSObject <UIApplicationDelegate>
@property (nonatomic, strong) UIWindow * alertWindow;
...
- (void)presentCustomAlert;
@end
Implementation:
@implementation MyAppDelegate
@synthesize alertWindow = _alertWindow;
...
- (void)presentCustomAlert
{
if (self.alertWindow == nil)
{
CGRect screenBounds = [[UIScreen mainScreen] bounds];
UIWindow * alertWindow = [[UIWindow alloc] initWithFrame:screenBounds];
alertWindow.windowLevel = UIWindowLevelAlert;
}
SomeViewController * myAlert = [[SomeViewController alloc] init];
alertWindow.rootViewController = myAlert;
[alertWindow makeKeyAndVisible];
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With