14

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.

Osa
  • 1,922
  • 7
  • 30
  • 51
  • @J.Doe Correct. My bad. [offset: from ScrollView it is then.](https://developer.apple.com/documentation/swiftui/scrollview) – Akaino Jun 05 '19 at 09:49
  • Look at my [post] (https://stackoverflow.com/questions/57258846/how-to-make-a-swiftui-list-scroll-automatically/58708206#58708206) about experiments with custom scroll view. – Asperi Nov 11 '19 at 13:21

1 Answers1

8

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 !!
                }
            }
        }
    }
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690