Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Height and Width of View or Screen in SwiftUI

I'm using a drag gesture to change the Hue/Saturation of a Color object. The idea is that you can drag across the screen and see all Hue values (0.0 - 1.0), and the same top to bottom with Saturation.

I require the size of the Screen (or view, this is a single view app) in order to normalize/convert the CGPoint values into a range between 0.0 - 1.0, but I am unable to find anyway to get this information. There are many threads discussing this, but they usually talk about how to set the width/heigh of a View when I just want to retrieve it.

I have everything functioning, just that I am using hardcoded values to normalize it.

like image 347
cmweeden Avatar asked Feb 01 '20 21:02

cmweeden


1 Answers

Look into GeometryReader. It allows you to get the size of the current view:

struct ContentView: View {
    
    var body: some View {
        GeometryReader { geo in
            VStack {
                Text("Hello World!")
                Text("Size:  (\(geo.size.width), \(geo.size.height))")
            }
        }
    }
}

And here is an example where you can drag on the screen to change the hue value:

struct ContentView: View {

    @State private var hue: CGFloat = 0
    
    var body: some View {
        GeometryReader { geo in
            ZStack {
                Color.white
                    .gesture(DragGesture().onChanged({ value in
                        self.hue = value.location.y / geo.size.height
                    }))
                
                VStack {
                    Text("Hello World!")
                    Text("Size:  (\(geo.size.width), \(geo.size.height))")
                    Text("Hue:  \(self.hue)")
                }.allowsHitTesting(false)
            }
        }
        .edgesIgnoringSafeArea(.all)
    }
}

GeometryReader breaking your view layout? Check out this gist.

like image 130
George Avatar answered Nov 15 '22 06:11

George