7

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 Answers 5

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

this was deprecated, how do you do this in swift 5?
13

Any view has a reference to the current window.

In a UIViewController:

self.view.window 

1 Comment

Hmm, I'm getting errors with that. UIWindow does not have a member named addSubview & UIWindow does not have a member names 'centre'. NB: I'm doing this on a UIView which is trying to add itself to the window when a method on it is called from a UIViewController.
4

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 } 

Comments

4

Swift 3 version:

let window :UIWindow = UIApplication.shared.keyWindow! 

1 Comment

Welcome to stackoverflow. This post was of very poor quality, and needed significant improvements to be useful. Please, could you expand your answer?
0

You get the first window with:

let window = UIApplication.shared.windows[0] 

Comments