问题
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?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
UIApplication *application = [UIApplication sharedInstance];
NSarray *appWindows = [NSArray arrayWithArray:application.windows];
UIWindow *mainWindow = [appWindows objectAtIndex:0];
I am not sure but this might help.
回答5:
In Swift:
UIApplication.sharedApplication().delegate?.window
回答6:
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.
回答7:
Swift 3
if let window = NSApplication.shared().windows.first {
// you can now modify window attributes
}
回答8:
Swift 3
class func sharedInstance() -> AppDelegate{
return UIApplication.shared.delegate as! AppDelegate
}
来源:https://stackoverflow.com/questions/17841097/get-applications-main-window