简体   繁体   English

ScrollView 获取/设置滚动 position 与 SwiftUI

[英]ScrollView get/set scroll position with SwiftUI

I'm trying to programmatically scroll to specific Y position in a ScrollView , when a button is clicked, How do i set the ScrollView position?我正在尝试以编程方式滚动到ScrollView中的特定 Y position ,当单击按钮时,如何设置ScrollView position?

ScrollView {
 Button(action: {

 }) {
    Text("Sign In").fontWeight(.heavy)        
 }
}

I want this button action, to access and change the ScrollView position.我想要这个按钮操作,以访问和更改 ScrollView position。

SwiftUI 2.0 SwiftUI 2.0

Since iOS 14 it is possible to do with ScrollViewReader (ie. some specific view in ScrollView container can be assigned identifier and via ScrollViewProxy.scrollTo to that view), like in below example由于 iOS 14 可以使用ScrollViewReader (即 ScrollView 容器中的某些特定视图可以分配标识符并通过ScrollViewProxy.scrollTo分配给该视图),如下例所示

Tested with Xcode 12b.用 Xcode 12b 测试。

struct DemoScrollToView: View {
    var body: some View {
        ScrollView {
            ScrollViewReader { sp in     // << here !!
                Button(action: {
                    withAnimation {
                        sp.scrollTo(80)            // << here !!
                    }
                }) {
                    Text("Sign In").fontWeight(.heavy)
                }

                ForEach(0..<100) { i in
                    Text("Item \(i)").padding().id(i)       // << here !!
                }
            }
        }
    }
}

I'm trying to programmatically scroll to specific Y position in a ScrollView , when a button is clicked, How do i set the ScrollView position ?我试图以编程方式滚动到ScrollView特定Y位置,单击按钮时,如何设置ScrollView位置?

ScrollView {
 Button(action: {

 }) {
    Text("Sign In").fontWeight(.heavy)        
 }
}

I want this button action, to access and change the ScrollView position.我希望此按钮动作可以访问和更改ScrollView的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM