Search code examples
iosuikituiwindowuiscenedelegateuiscene

UIWindow in SceneDelegate


Recently, I encountered a problem, which I have posted here, in stackoverflow. Apparently, the error was because a random UIWindow variable was used to display UI (and not the one in SceneDelegate).

Here's my understanding - Every time a scene is created (by user or the app), a UISceneSession is created to manage a UIScene, which can contain one or more UIWindows, each of which has views, which are displayed with the help of a view controller. Each UIScene will get a UISceneDelegate object to handle its lifecycle.

The error in my previous post makes sense now - since a random UIWindow object was used instead of the one in SceneDelegate.

But I still don't completely understand why a UIWindow was declared in the SceneDelegate by Xcode. There's a UIWindow object in UIWindowSceneDelegate (super class of my current SceneDelegate) and the documentation clearly explains that its a window associated with the scene. Why isn't that used and instead a new variable is created by Xcode while creating the project? If I need another window, then can I just add another UIWindow object to the current SceneDelegate? Is that a good practice?

@available (iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
    var window: UIWindow?

    // Remaining methods
}

I'm new to swift and iOS app development - any help to fill in these blanks would be greatly appreciated.


Solution

  • UIWindowSceneDelegate is not the superclass of your scene delegate. It is a protocol. It isn't an actual thing. It is merely a set of instructions telling the compiler what it would mean to adopt this protocol. Your SceneDelegate class does adopt the UIWindowSceneDelegate protocol. Therefore it must declare a window property of type UIWindow? — and it does so.

    Moreover, this property is the scene delegate's window; without it, you would have no window and the screen would be black. You could in fact set this property to a window that you make yourself; but you don't have to, and so you probably don't bother. You don't have to because the framework does it automatically for you as part of the scene-creation process.