SwiftUI - 如何获取 ScrollView 内容的大小(高度) [英] SwiftUI - How to get size (height) of ScrollView content
问题描述
我想确定我的(垂直)ScrollView
中内容的高度.
I want to determine the height of the content inside my (vertical) ScrollView
.
ScrollView {
//My Content
}
这可能吗?我尝试了一些东西,但似乎没有任何效果.
Is this possible? I've tried a few things but nothing seems to work.
不幸的是,简单地使用 GeometryReader
不起作用,因为无论 ScrollView
中有什么内容,它都会返回 10
的值
Unfortunately, using simply the GeometryReader
isn't working, since it returns a value of 10
no matter what content is inside the ScrollView
谢谢!
推荐答案
这里提供了一种实际获取 ScrollView
内容的 height
的方法.
Here is a way to actually get the height
of the ScrollView
content.
CZ54s 的回答看起来很直观,但它总是返回 10 的高度,这是不正确的!
CZ54s answer seems intuitive, but it always returns a height of 10 which is not correct!.
我们必须改为读取内容的高度.GeometryReader
直接在 ScrollView
内部不会这样做.一种可能的方法是使用 .background
/.overlay
.
We have to read the height of the content instead. GeometryReader
directly inside ScrollView
doesn't do that. A possible approach would be with .background
/.overlay
.
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) }
}
)
}
}
}
我们得到了 20500.0
的输出,这是正确的.
We get an output of 20500.0
which is correct.
这篇关于SwiftUI - 如何获取 ScrollView 内容的大小(高度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!