why is VStack not working in GeometryReader with scrollview?

旧时模样 提交于 2021-02-10 06:09:51

问题


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:

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:


回答1:


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
            }
        )
    }
}


来源:https://stackoverflow.com/questions/60965295/why-is-vstack-not-working-in-geometryreader-with-scrollview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!