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

最佳答案

使用 this 解决方案(以前简化)我做了一个例子,当按下按钮时将 ScrollView.content.offset 严格移动到顶部:

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

关于SwiftUI,如何滚动到顶部?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59080859/

10-11 19:22