如何從應用程序委託的視圖中顯示模態視圖控制器,最頂層?試圖從UIView中呈現模態視圖控制器,這讓我感到困惑。presentModalViewController from app delegate
回答
應用程序代理不管理視圖。您應該從第一個視圖控制器的-viewDidAppear:
方法中提供一個模式視圖控制器,該方法在-application:didFinishLaunchingWithOptions:
屏幕上顯示。
使用您的rootViewController
。您可以從任何視圖控制器子類呈現模態視圖控制器。如果你的root VC是一個的UITabBarController,那麼你可以做:
[self.tabBarController presentModalViewControllerAnimated:YES]
,或者如果它是一個導航控制器:
[self.navigationController presentModalViewControllerAnimated:YES]
等
編輯:MVC
通過試圖從視圖中呈現一個控制器,您打破了MVC模式。一般來說,視圖關注其外觀並暴露接口以將用戶界面狀態傳達給其控制器。例如,如果您的視圖中有一個UIButton
,並且您希望它顯示一個模式視圖控制器,則不要硬連線視圖來執行此操作。相反,當控制器實例化視圖時,控制器通過將其自身設置爲目標來配置該按鈕,以接收touchUpInside
動作,其中它可以呈現適當的模態視圖控制器。
視圖本身沒有(也不應該)具有這種上下文知識來完成控制器的工作。
最好的辦法是創建一個新的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
工程就像一個魅力。 – 2013-08-19 06:43:21
非常有幫助的答案 – Fattie 2013-11-16 18:25:30
- 1. presentModalViewController from UIModalTransitionStylePartialCurl viewController
- 2. Swift App delegate-> ViewController Cocoa
- 3. Mkdir from OSX app
- 4. 在App Delegate中設置Init VC?
- 5. App Delegate中的重新驗證代碼?
- 6. 從App Delegate調用PushViewController不起作用
- 7. 從App Delegate檢查屏幕上的UIAlertViews
- 8. presentModalViewController
- 9. iphone presentModalViewController
- 10. UINavigationController和presentModalViewController
- 11. presentModalViewController無法正常工作
- 12. Swift - 從App Delegate預載其他選項卡視圖
- 13. 在App Delegate中設置視圖控制器Xcode 5
- 14. 從App Delegate訪問另一個視圖控制器IBOutlet
- 15. 在輔助線程的主線程上執行App Delegate方法
- 16. 從View Controller中的App Delegate訪問變量
- 17. 如何從app delegate訪問uitabbarcontroller中的uinavigationcontroller內的uitableview?
- 18. 使用#define訪問App Delegate對象不起作用
- 19. 在App Delegate中啓動時顯示加載屏幕
- 20. Simple App Delegate方法顯示UIAlertController(在Swift中)
- 21. 我應該將我的UITabBarController放在App Delegate之外嗎?
- 22. presentmodalviewcontroller navigationcontroller
- 23. presentModalViewController iPhone
- 24. presentmodalviewcontroller navigationcontroller
- 25. 使用presentModalViewController添加視圖
- 26. CheckForIllegalCrossThreads,Thread&Delegate - Window Mobile
- 27. Genericising delegate/IAsyncResult calls
- 28. .delegate問題
- 29. CABasicAnimation with delegate crash
- 30. 使用$ .delegate()
其實我想從一個UIView呈現modalViewController,並試圖呈現這個在最上面的視圖 - 控制,任何想法? – adit 2012-01-11 19:20:07
模態視圖控制器只能由其他視圖控制器呈現。他們管理的視圖不知道他們自己的控制器,更不用說其他視圖控制器。 – 2012-01-11 19:22:43
雖然這個答案指出了一些OP的誤解,但它並沒有真正回答這個問題。請參閱我的答案:UIWindow – Steve 2012-01-11 19:25:19