Get Application's main window

女生的网名这么多〃 提交于 2019-12-04 23:40:31
Espresso

The UIApplicationDelegate usually has a reference to the "main window":

[[[UIApplication sharedApplication] delegate] window];

Furthermore, UIApplication has an array of windows [[UIApplication sharedApplication] windows].

See the UIApplication Class Reference.

I'm not 100% sure this works in every case but this should work:

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

The windows are ordered back to front so the main window should always be at index 0.

fpg1503

Swift 3.0 version of rmaddy's answer:

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.

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

I am not sure but this might help.

In Swift:

UIApplication.sharedApplication().delegate?.window

For me I was presenting a 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.

Swift 3

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

Swift 3

class func sharedInstance() -> AppDelegate{
        return UIApplication.shared.delegate as! AppDelegate
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!