SwiftUI,如何滚动到顶部? [英] SwiftUI, How to scroll to the top?

查看:49
本文介绍了SwiftUI,如何滚动到顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ScrollView,当我执行任何操作(例如单击按钮等)时,是否可以将视图滚动到顶部?

I am using ScrollView, and is that possible to scroll the view to the top when I do any actions, such as click button and etc?

推荐答案

Using this 解决方案(以前简化)我做了按下按钮时将 ScrollView.content.offset 严格移动到顶部的示例:

Using this solution (previously simplified) I made example of moving ScrollView.content.offset strict to the top when button pressed:

struct ScrollToTheTop: View {

    @State private var verticalOffset: CGFloat = 0.0
    @State private var gestureOffset: CGFloat = 0.0
    @State private var itemCount: Int = 200

    var body: some View {

        NavigationView {
            VStack {

                ScrollView(.vertical, showsIndicators: false) {

                    VStack {

                        ForEach(1...itemCount, id: \.self) { item in
                            Text("--- \(item) ---") // height 17.5
                        }

                    }

                }
                .content.offset(y: (self.verticalOffset + self.gestureOffset)
                    // all the content divided by 2 for zero position of scroll view
                    + CGFloat(17.5 * Double(self.itemCount/2)))
                    .gesture(DragGesture().onChanged( { value in
                        self.gestureOffset = value.translation.height
                    }).onEnded( { value in
                        withAnimation {
                            // here should calculate end position with value.predictedEndLocation.y
                            self.verticalOffset += value.translation.height
                            self.gestureOffset = 0.0
                        }
                    }))


            }.navigationBarItems(trailing: Button("To top!") {
                withAnimation {
                    self.verticalOffset = 0.0
                }
            })
        }

    }

}

如果这个例子合适,你必须改进DragGesture

if this example fits, you have to refine DragGesture

这篇关于SwiftUI,如何滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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