如何在 SwiftUI ScrollView 中以编程方式检测滚动方向
问题描述:
我想像 safari 一样按滚动方向显示或隐藏项目.向上滚动时隐藏,向下滚动时显示.
I want display or hide items by scroll direction just like safari. Hide something when scroll up, and show it when scroll down.
答
您将使用 GeometryReader 获取 ScrollView 中视图中一个的全局位置,以检测滚动方向.下面的代码将打印出当前的 midY 位置.根据 +/- 值,您可以显示或隐藏其他视图.
You would use GeometryReader to get the global position of one in the views in the ScrollView to detect the scroll direction. The code below will print out the current midY position. Dependent on the +/- value you could display or hide other views.
struct ContentView: View {
var body: some View {
ScrollView{
GeometryReader { geometry in
Text("Top View \(geometry.frame(in: .global).midY)")
.frame(width: geometry.size.width, height: 50)
.background(Color.orange)
}
}.frame(minWidth: 0, idealWidth: 0, maxWidth: .infinity, minHeight: 0, idealHeight: 0, maxHeight: .infinity, alignment: .center)
}
}