本文介绍了获取 SwiftUI ScrollView 的当前滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用新的 ScrollLViewReader,似乎可以以编程方式设置滚动偏移.

With the new ScrolLViewReader, it seems possible to set the scroll offset programmatically.

但我想知道是否也可以获取当前滚动位置?

But I was wondering if it is also possible to get the current scroll position?

看起来 ScrollViewProxy 只带有 scrollTo 方法,允许我们设置偏移量.

It seems like the ScrollViewProxy only comes with the scrollTo method, allowing us to set the offset.

谢谢!

推荐答案

之前可以阅读它.这是一个基于视图偏好的解决方案.

It was possible to read it and before. Here is a solution based on view preferences.

struct DemoScrollViewOffsetView: View {
    @State private var offset = CGFloat.zero
    var body: some View {
        ScrollView {
            VStack {
                ForEach(0..<100) { i in
                    Text("Item \(i)").padding()
                }
            }.background(GeometryReader {
                Color.clear.preference(key: ViewOffsetKey.self,
                    value: -$0.frame(in: .named("scroll")).origin.y)
            })
            .onPreferenceChange(ViewOffsetKey.self) { print("offset >> \($0)") }
        }.coordinateSpace(name: "scroll")
    }
}

struct ViewOffsetKey: PreferenceKey {
    typealias Value = CGFloat
    static var defaultValue = CGFloat.zero
    static func reduce(value: inout Value, nextValue: () -> Value) {
        value += nextValue()
    }
}

这篇关于获取 SwiftUI ScrollView 的当前滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:07