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

Time:11-17

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

CodePudding user response:

Try this one:

let height = view.bounds.size.height
let width = view.bounds.size.width
print("Width size:", view.bounds.size.width, "Width size:", view.bounds.size.height)

output iPhone 14 pro

output: Width size: 393.0 Height size: 852.0

CodePudding user response:

Use a GeometryReader - docs here: https://developer.apple.com/documentation/swiftui/geometryreader. Example usage:

struct MyTestView: View {
    
    var body: some View{
        VStack{
            GeometryReader{ geo in
                VStack {
                    Text("Width: \(geo.size.width)")
                    Text("Height: \(geo.size.height)")
                }
            }
        }
    }
}

geo.size is a CGSize - docs here: https://developer.apple.com/documentation/corefoundation/cgsize.

  • Related