Unexpected GeometryReader view behavior inside a VStack

Viewed 378

Can someone explain why:

GeometryReader positions its contents to the left top corner, not in the center. GeometryReader takes up all available space.

struct ContentView: View {
    var body: some View {
        VStack(alignment: .center) {
            GeometryReader { geo in
                    Text("Hello, World!")
                        .frame(width: geo.size.width * 0.7, height: 40)
                        .background(Color.red)
            }
            .background(Color.yellow)

            Text("More text")
                .background(Color.blue)
        }
    }
}

This is how it looks:

GeometryReader top left

I would expect it to position Text "Hello, World" view in the center.

1 Answers

First you need to make some critical changes to get what you're expecting. The reason it is appearing like this is because you're not using Geometry Reader in the way that you think it's supposed to be used. Geometry reader is essentially a way to get the parent view's size. Typically you won't use it to layout views and you'd still stick with VStack, ZStack, and HStack nested inside of the geometry reader. This is because the reader expands to take up as much space as possible across the X and Y planes. A typical structure to do what you're expecting might look like this. Which ultimately would center "Hello World" inside the center of the geometry reader.

GeometryReader { reader in 
    VStack {
         Spacer()
         HStack {
             Spacer()
             Text("Hello World")
             Spacer()
         Spacer()
    }
}
Related