iOS

Add a new UIWindow in Xcode11 or later

Xcode11UIWindow-en

How to add a new UIWindow in Xcode11 or later

How to write Xcode 10 or less

Until Xcode10, when I added a new window and wanted to display the alert of UIAlertViewController on that window, I wrote as follows.

let newWindow = UIWindow(frame: UIScreen.main.bounds) 
newWindow.rootViewController = UIViewController() 
newWindow.windowLevel = UIWindow.Level.alert + 1 
newWindow.makeKeyAndVisible() 

How to write when using Xcode 11 or above & UIScene

However, since Xcode11 / iOS13 started using SceneDelegate, the above writing method did not work well.
So if you add a Window as below, it works fine.

guard let windowScene = UIApplication.shared.connectedScenes
            .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene else { return }
let window = UIWindow(windowScene: windowScene)
// The rest is the same as above

You can now display modals and alerts by adding a new window instead of using an existing view controller.

UIWindow related extensions

When using UIWindow or keyWindow, it is convenient to create the following extension.

extension UIApplication {
    var windowScene: UIWindowScene? {
        return connectedScenes
            .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
    }

    // You can get the keyWindow as follows.
    var keyWindow: UIWindow? {
        return windowScene?.windows
            .first(where: { $0.isKeyWindow })
    }
}

I would appreciate it if you could point out any corrections.

0

COMMENT

Your email address will not be published. Required fields are marked *

CAPTCHA