Ask Your Question

Revision history [back]

GeometryReader is a view that provides us with a geometry object that contains the size and position of its parent view. Here's how you can use GeometryReader to adjust the size of a view to fit any parent of varying sizes:

struct ContentView: View {
    var body: some View {
        GeometryReader { geometry in
            Rectangle()
                .foregroundColor(.blue)
                .frame(width: geometry.size.width * 0.8, height: geometry.size.height * 0.5)
        }
        .background(Color.gray)
    }
}

In this example, we're using a Rectangle view as the content of our GeometryReader. We're then setting the frame of the rectangle to be 80% of the width and 50% of the height of the geometry object. This will ensure that our view is always 80% wide and 50% tall in relation to its parent.

We're also setting the background color of the GeometryReader to gray to make it easier to see the size and position of our view.

By using GeometryReader in this way, our view will resize itself automatically to fit any parent of varying sizes.