Ask Your Question
1

How can GeometryReader be implemented to adjust the size of this view to fit any parent of varying sizes?

asked 2022-06-26 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-04-22 10:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-26 11:00:00 +0000

Seen: 18 times

Last updated: Apr 22 '21