【问题标题】:How to detect scroll direction programmatically in SwiftUI ScrollView如何在 SwiftUI ScrollView 中以编程方式检测滚动方向
【发布时间】:2020-04-08 01:49:26
【问题描述】:

我想像 safari 一样按滚动方向显示或隐藏项目。向上滚动时隐藏,向下滚动时显示。

【问题讨论】:

  • 当您的滚动内容出现时,您可能会使用.onAppear() 进行计算。

标签: scrollview swiftui


【解决方案1】:

我认为,simultaneousGesture 是一个更好的解决方案,因为它不会阻塞 scrollView 事件。

ScrollView {

}
.simultaneousGesture(
       DragGesture().onChanged({
           let isScrollDown = 0 < $0.translation.height
           print(isScrollDown)
       }))

此方法仅在屏幕停止滚动时才检测到新的滚动

【讨论】:

  • 不幸的是,将DragGesture 应用于ScrollView 将导致onChanged 回调仅被触发一次,因为滚动视图默认处理这些事件。因此,这不会产生正确的行为。
【解决方案2】:

您可以使用 DragGesture 值

ScrollView {
...
}
.gesture(
   DragGesture().onChanged { value in
      if value.translation.height > 0 {
         print("Scroll down")
      } else {
         print("Scroll up")
      }
   }
)

【讨论】:

  • 不幸的是,将DragGesture 应用于ScrollView 将导致onChanged 回调仅被触发一次,因为滚动视图默认处理这些事件。因此,这不会产生正确的行为。
【解决方案3】:

您将使用 GeometryReader 在 ScrollView 的视图中获取一个的全局位置,以检测滚动方向。下面的代码将打印出当前的 midY 位置。根据 +/- 值,您可以显示或隐藏其他视图。

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

}

【讨论】:

  • 这看起来很有希望,并且绕过了 onChange 被触发一次。如何使用 midY 值来检测方向?还是设置一个状态变量?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 2019-11-02
相关资源
最近更新 更多