获取应用程序的主窗口

时间:2013-07-24 17:40:43

标签: ios objective-c uiwindow uiapplication

UIApplication有一个方法keyWindow,但是如果显示一个警报视图,那么这将返回警报视图的窗口,而不是应用程序的主窗口。

如何获取应用程序的主窗口?

8 个答案:

答案 0 :(得分:51)

UIApplicationDelegate通常会引用“主窗口”:

[[[UIApplication sharedApplication] delegate] window];

此外,UIApplication有一系列窗口[[UIApplication sharedApplication] windows]

请参阅UIApplication Class Reference

答案 1 :(得分:8)

我并非100%确定这种方法在每种情况下都有效,但这应该有效:

UIWindow *mainWindow = [UIApplication sharedApplication].windows[0];

窗口按顺序排序,因此主窗口应始终位于索引0处。

答案 2 :(得分:4)

rmaddy's answer的Swift 3.0版本:

let window = UIApplication.shared.windows.first

我还应该补充一点,因为iOS 8.0 UIAlertController已经取代UIAlertView并且是一个视图控制器,您可能不再面临创建新窗口的问题。

答案 3 :(得分:3)

UIApplication *application = [UIApplication sharedInstance];
NSarray *appWindows = [NSArray arrayWithArray:application.windows];
UIWindow *mainWindow = [appWindows objectAtIndex:0];

我不确定,但这可能有所帮助。

答案 4 :(得分:3)

在斯威夫特:

UIApplication.sharedApplication().delegate?.window

答案 5 :(得分:0)

对我来说,我提出的是popViewController

self.presentViewController(popViewController, animated: true, completion: nil)

然后在这个popViewController的<{1}} 我添加了一个子视图,这会导致控制台中的错误和显示错误。所以我必须找到另一种解决方案才能使它发挥作用。希望这会有所帮助。

答案 6 :(得分:0)

Swift 3

    if let window = NSApplication.shared().windows.first {
        // you can now modify window attributes
    }

答案 7 :(得分:-1)

Swift 3

class func sharedInstance() -> AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }