SwiftUI |从ScrollView获取当前滚动位置 [英] SwiftUI | Get current scroll position from ScrollView

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

问题描述

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

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获取当前滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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