How to remove a UIWindow? How to remove a UIWindow? ios ios

How to remove a UIWindow?


The correct way to hide a window is to set the hidden property to YES. To remove it from UIApplication's windows property you just release the window (in ARC you set all references to nil).

Of course you would want to have another window in place at this time.


Do not invoke -resignKeyWindow directly, it was meant to be overridden to execute some code when your UIWindows gets removed. In order to remove old window you need to create new instance of UIWindow and make it -makeKeyAndVisible, the old window will resign its key status. In iOS 4 it will even garbage collect your old UIWindow, provided you don't have any references to it. Doing this in iOS 3.x would have disastrous effects. Warned ya.


Here is how you can remove UIWindow on iOS 13 in a backward-compatible way. Tested on iOS 12, iOS 13, iPadOS with multi-window support:

extension UIWindow {    func dismiss() {        isHidden = true        if #available(iOS 13, *) {            windowScene = nil        }    }}

Usage:

// Detect key windowlet keyWindow = UIApplication.shared.windows.first { $0.isKeyWindow }// Dismiss key window (if any)keyWindow?.dismiss()