presentModalViewController从应用程序委托

我该如何从应用程序代表的视图展示模态视图控制器,最顶层? 试图从UIView中呈现一个模式视图控制器,这使我感到困惑。

应用程序代表不pipe理视图。 您应该在第一个视图控制器的-viewDidAppear:方法中显示一个模式视图控制器,该控制器放在屏幕上的应用程序-application:didFinishLaunchingWithOptions:

使用你的rootViewController 。 您可以从任何视图控制器子类呈现一个模式视图控制器。 如果你的根VC是一个UITabBarController,那么你可以这样做:

 [self.tabBarController presentModalViewControllerAnimated:YES] 

或者如果它的导航控制器:

 [self.navigationController presentModalViewControllerAnimated:YES] 

等等

编辑:MVC

通过尝试从视图中呈现控制器,您将打破MVC模式。 一般来说,一个视图是关于它的外观和暴露的接口来将用户界面状态传达给它的控制器。 例如,如果你的视图中有一个UIButton ,并且你希望它显示一个模式视图控制器,那么你不要硬连线视图来做这件事。 相反,当控制器实例化视图时,控制器通过将其自身设置为接收touchUpInside操作的目标来configuration该button,从而可以呈现合适的模式视图控制器。

这个观点本身并没有(也不应该)有这样的背景知识去做一个控制者的工作。

最好的方法是创build一个新的UIWindow ,设置它的windowLevel属性,并在窗口中显示你的UIViewController

这是UIAlertView的工作原理。

接口

 @interface MyAppDelegate : NSObject <UIApplicationDelegate> @property (nonatomic, strong) UIWindow * alertWindow; ... - (void)presentCustomAlert; @end 

执行:

 @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