Per Apple discussion on UIScreen.main
deprecation:
Apple discourages the use of this symbol. Use a UIScreen instance
found through context instead. For example, reference the screen that
displays a view through the screen property on the window scene
managing the window containing the view.
Here is an extension to find the UIScreen instance through context:
extension UIViewController {
func screen() -> UIScreen? {
var parent = self.parent
var lastParent = parent
while parent != nil {
lastParent = parent
parent = parent!.parent
}
return lastParent?.view.window?.windowScene?.screen
}
}
For reference, this is the same UIScreen
instance associated with the windowScene
in the SceneDelegate:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(frame: windowScene.coordinateSpace.bounds)
window?.windowScene = windowScene
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
let screen = windowScene.screen
configureNavigationBar()
}