Jonathan.
Jonathan.

Reputation: 55554

Get Application's main window

UIApplication has a method keyWindow, however if an alert view is showing then this returns the window of the alert view and not the main window of the application.

How can I get the app's main window?

Upvotes: 39

Views: 44895

Answers (8)

Espresso
Espresso

Reputation: 4752

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.

Upvotes: 60

Ved Rauniyar
Ved Rauniyar

Reputation: 1589

Swift 3

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

Upvotes: -2

fpg1503
fpg1503

Reputation: 7582

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.

Upvotes: 7

Ted Lowery
Ted Lowery

Reputation: 1545

Swift 3

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

Upvotes: 0

AnthonyR
AnthonyR

Reputation: 3545

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.

Upvotes: 0

Glauco Neves
Glauco Neves

Reputation: 3539

In Swift:

UIApplication.sharedApplication().delegate?.window

Upvotes: 3

RKY
RKY

Reputation: 266

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

I am not sure but this might help.

Upvotes: 3

rmaddy
rmaddy

Reputation: 318814

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.

Upvotes: 12

Related Questions