如何使用 UIApplication 获取我的 UIWindow?
我只有一个窗口,我尝试过
UIWindow* mWindow = [[UIApplication sharedApplication] keyWindow];
,但返回为零。
我也尝试过:
UIWindow* mWindow = (UIWindow*)[[UIApplication sharedApplication].windows objectAtIndex:0];
但这引发了异常,应用程序关闭,当我尝试打印时,
[[UIApplication sharedApplication].windows count]
它打印了 0
注意:我将其放入我唯一的视图控制器的 viewDidLoad 方法中,这完全是一个新的基于 iPad 视图的应用程序,所以我没有更改任何内容,只是想获取窗口
请帮我获取这个对象
I have only one window and I tried
UIWindow* mWindow = [[UIApplication sharedApplication] keyWindow];
but this returned nil.
I also tried:
UIWindow* mWindow = (UIWindow*)[[UIApplication sharedApplication].windows objectAtIndex:0];
But this raised an exception and the app closed, when I tried to print out
[[UIApplication sharedApplication].windows count]
It printed 0
Note: I am putting this in my only view controller's viewDidLoad method and this is completely a new iPad View Based Application so I changed nothing, just trying to get the window
Please help me to get this object
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您的主窗口是 AppDelegate 的出口(应该是这种情况),您可以简单地使用
If your main window is an outlet of your AppDelegate (which should be the case), you may simply use
最简单的方法是从应用程序委托获取窗口:
Easiest way is to get the window from the app delegate instead:
在应用委托中调用
[window makeKeyAndVisible]
之前,不会设置应用程序的关键窗口。在此调用之前,您的 UIViewController 可能已从 NIB 加载。这解释了为什么 keyWindow 返回 nil。幸运的是,您的视图控制器不需要通过 UIApplication 来获取窗口。你可以这样做:
Your application's key window isn't set until
[window makeKeyAndVisible]
gets called in your app delegate. Your UIViewController is probably being loaded from a NIB before this call. This explains whykeyWindow
is returning nil.Luckily, your view controller doesn't need to go through UIApplication to get the window. You can just do:
对于 iOS 13+,您应该使用:
With iOS 13+ you should use:
您可以通过多种方式实现这一目标。我喜欢使用以下之一。
当您只需要访问一次时,请使用此选项。
如果您需要多次访问 UIWindow,我建议扩展一个类。我喜欢扩展
UIViewController
。You can achieve this in multiple ways. I like to use one of the following.
Use this when you need to access it just once.
If you need to access the
UIWindow
multiple times, I would suggest extending a class. I like to extend theUIViewController
.