Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is VStack not working in GeometryReader with scrollview?

My scrollview with vStack worked (in AppleTV - i did not test in iOS) without GeometryReader.

Then i added the geometryreader and the VStack "collapses" like a ZStack.

What can i do to solve this? (and yes, i need the geometryreader ;))

struct ContentView: View {

    @State var offset : CGFloat = 0

    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            VStack(alignment: .leading) {
                GeometryReader { geometry -> AnyView in
                    let newOffset = geometry.frame(in: .global).minY
                    if newOffset != self.offset {
                        self.offset = newOffset
                        print("new offset",newOffset)
                    }
                    return AnyView (
                        ForEach (0..<5) { _ in
                            Text("umpf")
                        }
                    )
                }
            }
        }
    }
}

Result:

enter image description here

and this code works as desired:

struct ContentView: View {

    @State var offset : CGFloat = 0

    var body: some View {
        ScrollView(.vertical, showsIndicators: false) {
            VStack(alignment: .leading) {
//                GeometryReader { geometry -> AnyView in
//                    let newOffset = geometry.frame(in: .global).minY
//                    if newOffset != self.offset {
//                        self.offset = newOffset
//                        print("new offset",newOffset)
//                    }
//                    return AnyView (
                        ForEach (0..<5) { _ in
                            Text("umpf")
                        }
            //        )
        //        }
            }
        }
    }
}

result: enter image description here

like image 740
Chris Avatar asked Oct 19 '25 02:10

Chris


1 Answers

Let me suppose that initially you wanted this (and it does not break ScrollView layout & scrolling)

var body: some View {
    ScrollView(.vertical, showsIndicators: false) {
        VStack(alignment: .leading) {
            ForEach (0..<5) { _ in
                Text("umpf")
            }
        }.background(
            GeometryReader { geometry -> Color in
                let newOffset = geometry.frame(in: .global).minY
                if newOffset != self.offset {
                    self.offset = newOffset
                    print("new offset",newOffset)
                }
                return Color.clear
            }
        )
    }
}
like image 57
Asperi Avatar answered Oct 22 '25 07:10

Asperi