【问题标题】:why is VStack not working in GeometryReader with scrollview?为什么 VStack 不能在带有滚动视图的 GeometryReader 中工作?
【发布时间】:2020-04-01 07:05:37
【问题描述】:

我使用 vStack 的滚动视图在没有 GeometryReader 的情况下工作(在 AppleTV 中 - 我没有在 iOS 中测试)。

然后我添加了几何读取器,并且 VStack 像 ZStack 一样“折叠”。

我能做些什么来解决这个问题? (是的,我需要几何阅读器;))

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

结果:

并且此代码可以按需要工作:

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

结果:

【问题讨论】:

    标签: swiftui geometryreader


    【解决方案1】:

    让我假设您最初想要这个(并且它不会破坏 ScrollView 布局和滚动)

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

    【讨论】:

    • 这正是我想要的,谢谢你,你是我的英雄! ;)
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多