ios 获取应用程序的主窗口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17841097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Application's main window
提问by Jonathan.
UIApplication has a method keyWindow
, however if an alert view is showing then this returns the window of the alert view and not the main window of the application.
UIApplication 有一个方法keyWindow
,但是如果显示警报视图,则返回警报视图的窗口,而不是应用程序的主窗口。
How can I get the app's main window?
如何获取应用程序的主窗口?
回答by Espresso
The UIApplicationDelegate
usually has a reference to the "main window":
在UIApplicationDelegate
通常的“主窗口”的参考:
[[[UIApplication sharedApplication] delegate] window];
Furthermore, UIApplication
has an array of windows [[UIApplication sharedApplication] windows]
.
此外,UIApplication
还有一系列 windows [[UIApplication sharedApplication] windows]
。
See the UIApplication Class Reference.
回答by rmaddy
I'm not 100% sure this works in every case but this should work:
我不是 100% 确定这在每种情况下都有效,但这应该有效:
UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];
The windows are ordered back to front so the main window should always be at index 0.
窗口从后到前排序,因此主窗口应始终位于索引 0。
回答by fpg1503
Swift 3.0 version of rmaddy's answer:
Swift 3.0 版rmaddy 的回答:
let window = UIApplication.shared.windows.first
I also should add that since iOS 8.0 UIAlertController
has replaced UIAlertView
and being a view controller you may no longer face the issue of new windows being created.
我还应该补充一点,由于 iOS 8.0UIAlertController
已被替换UIAlertView
并成为视图控制器,您可能不再面临创建新窗口的问题。
回答by RKY
UIApplication *application = [UIApplication sharedInstance];
NSarray *appWindows = [NSArray arrayWithArray:application.windows];
UIWindow *mainWindow = [appWindows objectAtIndex:0];
I am not sure but this might help.
我不确定,但这可能会有所帮助。
回答by Glauco Neves
In Swift:
在斯威夫特:
UIApplication.sharedApplication().delegate?.window
回答by AnthonyR
For me I was presenting a popViewController
对我来说,我正在展示一个 popViewController
self.presentViewController(popViewController, animated: true, completion: nil)
and then in the viewDidLoad()
of this popViewController I was adding a subview, this causes the error in the console and a display bug. So I have to find another solution to make it work. Hope this helps.
然后在viewDidLoad()
这个 popViewController 中我添加了一个 subview,这会导致控制台中的错误和显示错误。所以我必须找到另一个解决方案来使它工作。希望这可以帮助。
回答by Ted Lowery
Swift 3
斯威夫特 3
if let window = NSApplication.shared().windows.first {
// you can now modify window attributes
}
回答by Ved Rauniyar
Swift 3
斯威夫特 3
class func sharedInstance() -> AppDelegate{
return UIApplication.shared.delegate as! AppDelegate
}