45

我只有一个窗口,我试过了

UIWindow* mWindow = [[UIApplication sharedApplication] keyWindow];

但这返回为零。

我也试过:

UIWindow* mWindow = (UIWindow*)[[UIApplication sharedApplication].windows objectAtIndex:0];

但这引发了一个异常并且应用程序关闭了,当我试图打印出来时

[[UIApplication sharedApplication].windows count]

它打印了 0

注意:我把它放在我唯一的视图控制器的 viewDidLoad 方法中,这完全是一个新的基于 iPad 视图的应用程序,所以我什么也没做,只是试图获取窗口

请帮我得到这个对象

4

4 回答 4

49

如果您的主窗口是 AppDelegate 的出口(应该是这种情况),您可以简单地使用

MyAppDelegate* myDelegate = (((MyAppDelegate*) [UIApplication sharedApplication].delegate));
[myDelegate.window ...]
于 2010-09-23T20:41:55.017 回答
42

最简单的方法是从应用程序委托中获取窗口:

UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];
// Do something with the window now
于 2013-03-25T19:25:30.040 回答
20

[window makeKeyAndVisible]在您的应用程序委托中调用之前,您的应用程序的关键窗口不会设置。您的 UIViewController 可能是在此调用之前从 NIB 加载的。这解释了为什么keyWindow返回 nil。

幸运的是,您的视图控制器不需要通过 UIApplication 来获取窗口。你可以这样做:

UIWindow *mWindow = self.view.window;
于 2010-09-23T20:51:14.630 回答
6
[[[UIApplication sharedApplication] windows] objectAtIndex:0]; // You can also check the count of this to make sure, because if there are no windows it will crash.
于 2011-08-04T00:21:53.057 回答