如何在 SwiftUI ScrollView 中以编程方式检测滚动方向 [英] How to detect scroll direction programmatically in SwiftUI ScrollView

查看:65
本文介绍了如何在 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)
}

}

这篇关于如何在 SwiftUI ScrollView 中以编程方式检测滚动方向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆