Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GeometryReader unwanted full height/width behaviour

Tags:

swiftui

I'm using the GeometryReader for making sure that an image is never wider than half of the screen's width. However, it messes up the rest of my view as the GeometryReader requests the full height/width of the View (as shown in the image with the green BG). As if it inserts unwanted Spacer().

struct ContentView: View {
    var body: some View {
        VStack{
            VStack {
                GeometryReader{ g in
                    HStack{
                        Text("Text Left").background(Color.yellow)
                        Image(systemName: "checkmark")
                            .resizable()
                            .aspectRatio(contentMode:.fit)
                            .frame(maxWidth: g.size.width/2)
                    }.background(Color.yellow)
                }.background(Color.green)
            }
            Text("Bottom Text")

            // This Spacer should push the "Bottom Text" right below the other Text and Image
            Spacer()
        }
    }
}

enter image description here

If I remove the GeometryReader and set the width to a fixed size, it works as expected and the green BG does not show up.

struct ContentView: View {
    var body: some View {
        VStack{
            VStack {
                HStack{
                    Text("Text Left").background(Color.yellow)
                    Image(systemName: "checkmark")
                        .resizable()
                        .aspectRatio(contentMode:.fit)
                        .frame(maxWidth: 200)
                }.background(Color.yellow)
            }.background(Color.green)
            Text("Bottom Text")
            Spacer()
        }
    }
}

Is this a bug or how can the dynamic width be achieved with the GeometryReader?

enter image description here

like image 573
simibac Avatar asked Dec 02 '19 15:12

simibac


1 Answers

why do you set the geometryreader inside vstack? maybe you have a reason...but this way, i think, works as you want it?!

But yeah, you are right, the thing with the geometryreader is weird...

 GeometryReader{ g in

            VStack{
                VStack {
                    HStack{
                        Text("Text Left").background(Color.yellow)
                        Image(systemName: "checkmark")
                            .resizable()
                            .aspectRatio(contentMode:.fit)
                            .frame(maxWidth: g.size.width/2)
                            .background(Color.red)
                    }.background(Color.yellow)

                }
                Text("Bottom Text")

                // This Spacer should push the "Bottom Text" right below the other Text and Image
                Spacer()
            }
        }.background(Color.green)
like image 78
Chris Avatar answered Nov 11 '22 14:11

Chris