Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to get the screen size on iOS, after UIScreen.main deprecation

Tags:

ios

swift

swiftui

I always used UIScreen.main.bounds.size to get the screen size on iOS and worked fine.

Now (in iOS 16, I believe) when I try to access the screen size with the "main" instance of UIScreen a warning is displayed:

"main' will be deprecated in a future version of iOS: Use a UIScreen instance found through context instead: i.e, view.window.windowScene.screen

So my question is: What is the correct way to get the screen size? for simplicity let's imagine we are on the iPhone with, consequently, only one screen available. Thank you

like image 321
Luca Avatar asked Sep 12 '25 17:09

Luca


1 Answers

extension UIWindow {
    static var current: UIWindow? {
        for scene in UIApplication.shared.connectedScenes {
            guard let windowScene = scene as? UIWindowScene else { continue }
            for window in windowScene.windows {
                if window.isKeyWindow { return window }
            }
        }
        return nil
    }
}


extension UIScreen {
    static var current: UIScreen? {
        UIWindow.current?.screen
    }
}

This way, you can use this anywhere, just like you could with the UIScreen.main.

usage

UIScreen.current?.bounds.size
like image 133
eastriver lee Avatar answered Sep 15 '25 08:09

eastriver lee