ScrollView get/set scroll position with SwiftUI

Viewed 8703

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 {
 Button(action: {

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

I want this button action, to access and change the ScrollView position.

1 Answers

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

Tested with 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 !!
                }
            }
        }
    }
}
Related