Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

like image 821
Osa Avatar asked Jun 05 '19 08:06

Osa


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 !!
                }
            }
        }
    }
}
like image 155
Asperi Avatar answered Oct 20 '22 00:10

Asperi