I've created a new project using Xcode 11. I'm used to creating my UIWindow
's root view controller programmatically and I first noticed this new SceneDelegate file. After some research I found an article describing how to create root view controller using this new UIScene
API and it seems to work properly. However, I couldn't find a way to do the same thing for lower iOS versions because AppDelegate class now does not have a window
property anymore. So my question is how do I create a root view controller programmatically for other iOS versions?
Here's the code if someone faces the same thing.
Code taken from this article.
In your SceneDelegate file:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let windowScene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(frame: windowScene.coordinateSpace.bounds)
self.window?.windowScene = windowScene
let controller = UIViewController()
let navigationController = UINavigationController(rootViewController: controller)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
}
In your AppDelegate file:
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 13.0, *) { return true }
self.window = UIWindow(frame: UIScreen.main.bounds)
let controller = UIViewController()
let navigationController = UINavigationController(rootViewController: controller)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
It is important to hold UIWindow
in a variable in order for it to show up.