RobertL
RobertL

Reputation: 14894

In swiftUI, how do I get the frame for the screen my app is running on?

I need the current screen size in points. Could someone please show sample Swift code that gets the screen width and height?

Upvotes: 0

Views: 476

Answers (2)

RobertL
RobertL

Reputation: 14894

Asperi's answer is what I was looking for. Thanks. I've been so bewildered (and bedazzled) trying to learn swiftUI that I didn't think of the obvious. Duh...

To answer the question, here is code for a demo app:

import SwiftUI

struct ContentView: View {
   let w = UIScreen.main.bounds.size.width
   let h = UIScreen.main.bounds.size.height

    var body: some View {
      VStack() {
      Text(String(format: "width: %4.1f",w))
      Text(String(format: "height: %4.1f", h))
    }
   }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 0

UIChris
UIChris

Reputation: 621

you can easily achieve what you are looking for with GeometryReader, like so:

    GeometryReader { geometry in 
            VStack {
                 Text("Hope this helps!")
            }
            .frame(width: geometry.size.width, height: geometry.size.height)
     }

Upvotes: 1

Related Questions