Adding Views to the Window - codepath/ios_guides GitHub Wiki

All views in iOS belong to a window. A window is just a view with a few special properties. Normally, iOS applications only have a single window. It is occasionally useful to add views directly to a window or even create multiple windows.

You can add a view to the window directly if you want to easily cover all other views, e.g., the navigation bar and tab bar. For example, you might implement a custom alert view or action sheet by adding a view to the window.

If you create a new window (this is rare), you can also choose its level, which can be used to cover the status bar, alert views, or the keyboard.

Step 1: Getting the Window

Starting in iOS 13, every visible window belongs to a UIWindowScene, and UIApplication.shared.keyWindow was deprecated because a single application-wide key window is no longer well-defined once an app supports multiple scenes. The compiler emits:

'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes

If you already have a UIView (for example, inside a view controller), the simplest replacement is to read the view's own window. This is also the most reliable answer in a multi-scene app, because the view is already attached to the correct scene:

let window = imageView.window

If you do not have a view handy, find the foreground-active scene and ask it for its key window:

let window = UIApplication.shared.connectedScenes
    .compactMap { $0 as? UIWindowScene }
    .first { $0.activationState == .foregroundActive }?
    .keyWindow

UIWindowScene.keyWindow is available in iOS 15 and later. To support iOS 13 and 14, replace the trailing ?.keyWindow with ?.windows.first(where: { $0.isKeyWindow }).

The result is an Optional<UIWindow>. It will be nil early in launch (before any scene has activated) or if no scene is currently in the foreground, so unwrap before use.

Step 2: Adding a View

The coordinate (0,0) of the window is at the top left of the phone. Its sometimes useful to get the coordinate of an existing view in the coordinate system of the window. That will account for things like the status bar and the navigation bar.

For example, if there is an image view embedded in some other view, you can get its frame in the coordinate system of the window by doing the following:

let frame = window!.convert(imageView.frame, from: containerView)

In the example above, the imageView is a subview of containerView. The new frame variable is the coordinate of the imageView if it were a subview of the window.

To add a view to the window, simply use the add or insert subview methods.

window!.addSubview(imageView)
⚠️ **GitHub.com Fallback** ⚠️