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 Answers5

16

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.

Silis Alin
  • 140
  • 2
  • 13
13

Any view has a reference to the current window.

In a UIViewController:

self.view.window
Justus1
  • 473
  • 1
  • 4
  • 13
  • 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. –  Oct 17 '14 at 14:33
4

Swift 3 version:

let window :UIWindow = UIApplication.shared.keyWindow!
superarts.org
  • 7,009
  • 1
  • 58
  • 44
  • Welcome to stackoverflow. This post was of very poor quality, and needed significant improvements to be useful. Please, could you expand your answer? – Kenzo_Gilead Apr 30 '17 at 09:13
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
}
CodeBender
  • 35,668
  • 12
  • 125
  • 132
0

You get the first window with:

let window = UIApplication.shared.windows[0]
vvolf
  • 23
  • 6