SwiftUI - 如何获取 ScrollView 内容的大小(高度)

Mof*_*waw 10 ios swift swiftui

我想确定我的(垂直)内容的高度ScrollView

ScrollView {  
    //My Content
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?我尝试了一些方法,但似乎没有任何作用。

不幸的是,简单地使用 theGeometryReader是行不通的,因为10无论 the 中的内容是什么,它都会返回一个值ScrollView

谢谢!

Mof*_*waw 29

解决方案是在GeometryReader内部添加.background/.overlay修饰符。这使得可以读取ScrollView内容的高度。

struct ContentView: View {

    var body: some View {
        ScrollView {
            ForEach(0..<1000) { i in
                Text("\(i)")
            }
            .background(
                GeometryReader { proxy in
                    Color.clear.onAppear { print(proxy.size.height) }
                }
            )
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

20500.0我们得到了正确的输出。

  • 令人惊讶的是,这也适用于 LazyVStack,并且具有合理的性能! (2认同)