Last active
June 21, 2024 05:06
-
-
Save alexpaul/875d1c8ce45a5f536d0c81087285f4d8 to your computer and use it in GitHub Desktop.
Getting access to the SceneDelegate window object in Xcode 11. SceneDelegate. Reset application window. Reset window. Reset rootviewcontroller. Root view controller. Scene delegate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// accessing the window and changing the root view controller property | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// getting access to the window object from SceneDelegate | |
guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, | |
let sceneDelegate = windowScene.delegate as? SceneDelegate | |
else { | |
return | |
} | |
let viewcontroller = UIViewController() | |
viewcontroller.view.backgroundColor = .blue | |
sceneDelegate.window?.rootViewController = viewcontroller | |
} | |
// extension for resetting the window on a UIKit application | |
extension UIViewController { | |
private func resetWindow(with vc: UIViewController?) { | |
guard let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate else { | |
fatalError("could not get scene delegate ") | |
} | |
sceneDelegate.window?.rootViewController = vc | |
} | |
func showViewController(with id: String) { | |
let vc = storyboard?.instantiateViewController(identifier: id) | |
resetWindow(with: vc) | |
} | |
} | |
// example case of resetting the window from a login view controller | |
// this will transition from a login vc to a navigation controller with the app logic | |
@IBAction func explore(_ sender: UIButton) { | |
showViewController(with: "BBQNavController") | |
} |
@2020KamelAlaghbari, window
isn't in the UISceneDelegate prototype, but when I create a new project (iOS, Storyboard) using Xcode 13.4.1, the project includes a class called SceneDelegate, that conforms to UIWindowSceneDelegate, that includes a var window: UIWindow?.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@alexpaul
Value of type 'SceneDelegate' has no member 'window'
Error with code code
// extension for resetting the window on a UIKit application
extension UIViewController {
private func resetWindow(with vc: UIViewController?) {
guard let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate else {
fatalError("could not get scene delegate ")
}
sceneDelegate.window?.rootViewController = vc
}
func showViewController(with id: String) {
let vc = storyboard?.instantiateViewController(identifier: id)
resetWindow(with: vc)
}
}
error