2012-01-11 57 views

回答

6

應用程序代理不管理視圖。您應該從第一個視圖控制器的-viewDidAppear:方法中提供一個模式視圖控制器,該方法在-application:didFinishLaunchingWithOptions:屏幕上顯示。

+0

其實我想從一個UIView呈現modalViewController,並試圖呈現這個在最上面的視圖 - 控制,任何想法? – adit 2012-01-11 19:20:07

+1

模態視圖控制器只能由其他視圖控制器呈現。他們管理的視圖不知道他們自己的控制器,更不用說其他視圖控制器。 – 2012-01-11 19:22:43

+0

雖然這個答案指出了一些OP的誤解,但它並沒有真正回答這個問題。請參閱我的答案:UIWindow – Steve 2012-01-11 19:25:19

11

使用您的rootViewController。您可以從任何視圖控制器子類呈現模態視圖控制器。如果你的root VC是一個的UITabBarController,那麼你可以做:

[self.tabBarController presentModalViewControllerAnimated:YES] 

,或者如果它是一個導航控制器:

[self.navigationController presentModalViewControllerAnimated:YES] 

編輯:MVC

通過試圖從視圖中呈現一個控制器,您打破了MVC模式。一般來說,視圖關注其外觀並暴露接口以將用戶界面狀態傳達給其控制器。例如,如果您的視圖中有一個UIButton,並且您希望它顯示一個模式視圖控制器,則不要硬連線視圖來執行此操作。相反,當控制器實例化視圖時,控制器通過將其自身設置爲目標來配置該按鈕,以接收touchUpInside動作,其中它可以呈現適當的模態視圖控制器。

視圖本身沒有(也不應該)具有這種上下文知識來完成控制器的工作。

+2

如果'rootViewController'已經呈現模態視圖控制器,則不起作用。 – Steve 2012-01-11 19:34:49

+0

是真的,這只是一個例子。我不知道OP應用的完整邏輯。同意所有理解適當的技術是更好的,這樣你就可以在必要時完全知道你正在做什麼。 – XJones 2012-01-11 19:37:46

+0

一個基於UIWindow的方法總是可以工作,不需要定製邏輯......就像一個'UIAlertView'一樣。 – Steve 2012-01-11 19:38:48

10

最好的辦法是創建一個新的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 
+0

工程就像一個魅力。 – 2013-08-19 06:43:21

+0

非常有幫助的答案 – Fattie 2013-11-16 18:25:30

相關問題