如何在swift应用程序中获取keyWindow引用? [英] How do I get the keyWindow reference in a swift app?
问题描述
在UIViewController的viewDidLoad方法中的Objective-C中我这样做是为了在我的iOS应用程序中获取keyWindow引用:
In Objective-C in the viewDidLoad method of a UIViewController I do this to get the keyWindow reference in my iOS app:
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
所以,我将这个视图控制器移植到Swift中,我在viewDidLoad调用中执行此操作:
So, I am porting this view controller into Swift and I do this one the viewDidLoad call:
let window = UIApplication.sharedApplication().keyWindow
我试图理解为什么窗口是零。当我在该行之后放置一个断点时,然后在控制台中检查窗口,我得到了这个:
I am trying to understand why the window is nil. When I put a breakpoint right after that line I then inspect window in the console and I get this:
(lldb) po window
nil
如何让窗口成为我的应用程序的keyWindow的有效引用在swift?
How can I get window to be a valid reference to the keyWindow of my application in swift?
推荐答案
当我在swift中搜索窗口时,我遇到了这个问题。如果你想得到窗口而不是keyWindow,试试这个:
I came to this question when I was searching for getting window in swift. If you want to get window instead of keyWindow, try this:
if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {
MBProgressHUD.show(text, view:window)
}
更新了Swift 3 :(感谢@Trevor)
Updated for Swift 3: (Thanks @Trevor)
if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
MBProgressHUD.show(text, view:window)
}
这篇关于如何在swift应用程序中获取keyWindow引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!