Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIScreen.main is deprecated, what are other solutions other than GeometryReader? [closed]

Tags:

ios

swift

swiftui

I'm targeting iOS 16 for my app in which I access the screen height and width using UIScreen.main.bounds.width and UIScreen.main.bounds.height so I can draw views based on these two values. I'm assigning these two values to two CGFloat properties in the view struct as follows:

struct ContentView: View {
var width: CGFloat = UIScreen.main.bounds.width
var height: CGFloat = UIScreen.main.bounds.height
var fontSize: CGFloat
var body: some View {
    // draw views here using width and height properties

 }

Xcode is showing a warning message saying 'main' will be deprecated in a future version of iOS: use a UIScreen instance found through context instead: i.e, view.window.windowScene.screen

I'm not sure how to apply the answer here to my use case and I don't want to use GeometryReader since it just messes up the overall layout.

Any suggestions on how to obtain screen width and height in an app targeting iOS 16 and above without using GeometryReader?

like image 233
abs8090 Avatar asked Dec 21 '25 22:12

abs8090


1 Answers

Swift 5.5

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            GeometryReader { proxy in
                ContentView()
                    .environment(\.mainWindowSize, proxy.size)
            }
        }
    }
}

struct ContentView: View {   
    
    @Environment(\.mainWindowSize) var windowSize
    
    var body: some View {
        ZStack {
            Text("Hello, world!")
                .frame(width: windowSize.width/2, height: windowSize.height)
                .background(Color.blue)
        }
    }
}

private struct MainWindowSizeKey: EnvironmentKey {
    static let defaultValue: CGSize = .zero
}

extension EnvironmentValues {
    var mainWindowSize: CGSize {
        get { self[MainWindowSizeKey.self] }
        set { self[MainWindowSizeKey.self] = newValue }
    }
}

image_example

like image 77
MaatheusGois Avatar answered Dec 23 '25 13:12

MaatheusGois



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!