iosobjective-ciphoneuiwindowuiapplication

What is the difference between UIApplication.sharedApplication.delegate.window and UIApplication.sharedApplication.keyWindow?


Can anyone help me understand the difference between the following two lines:

[UIApplication.sharedApplication.delegate.window addSubview:myView];
[UIApplication.sharedApplication.keyWindow addSubview:myView];

Solution

  • They could be the same on iOS. When they are different, usually you are presenting another window other than the app delegate's main window. Your app can have many windows but only the keyWindow is the window that is visible on the screen and receiving events (example could be a UIAlert when visible and receiving events it is the keywindow) reference: https://developer.apple.com/library/content/documentation/WindowsViews/Conceptual/WindowAndScreenGuide/WindowScreenRolesinApp/WindowScreenRolesinApp.html

    from the documentation:

    The window to use when presenting a storyboard. This property contains the window used to present the app’s visual content on the device’s main screen.

    i.e this is the property window that you have in your AppDelegate.h file.

    This property holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible message.

    On iOS you call makeKeyAndVisible in your AppDelegate.m inside

    application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    You made the created appDelegate window the keyWindow. Usually, bank apps switch the key window when the app is put in the background to protect the users sensitive information when the home button is doubled tapped and switch back to the main delegate window when the app is in foreground.

    This answer is in collaboration with: @SipkeSchoorstra, @D-Mx and @andyDarwin