6
votes

I need to add a view directly to the window. I can do this by accessing the window object on the AppDelegate via UIApplication. I intend on making this code as reusable as possible though which makes that method unhelpful. How can I access the UIWindow programmatically without using AppDelegate?

I'm coding in Swift but Objective-C examples may be helpful too.

5

5 Answers

14
votes

Ok, figured this one out myself. You can access it like this:

var window : UIWindow = UIApplication.sharedApplication().keyWindow

Swift 5:

var window : UIWindow = UIApplication.shared.keyWindow

Note that keyWindow was deprecated in iOS 13.0. If you're targeting iOS 13.0 or higher, refer to this.

12
votes

Any view has a reference to the current window.

In a UIViewController:

self.view.window
4
votes

The following works with Swift 4 and will safely unwrap the UIWindow so that a force cast is not required:

if let window = UIApplication.shared.keyWindow { 
    // Do stuff
}
4
votes

Swift 3 version:

let window :UIWindow = UIApplication.shared.keyWindow!
0
votes

You get the first window with:

let window = UIApplication.shared.windows[0]