Search code examples
iosswiftswiftuiswiftui-form

How to scroll a Form to a specific UI element in SwiftUI


I have a form on a SwiftUI NavigationView. The form has no special elements, only the standard ones: TextField, DatePicker, and some Buttons

I would like to scroll programmatically to a specific element. How can I achieve this?

ScrollViewReader does not seem to work with forms.

ScrollViewReader { p in
  Form {
    ....
    Button(action: {
      p.scrollTo(150)
    }) {
      Text(self.label)
    }
}

Solution

  • Give id to every element and pass this id to the .scrollTo(id) method. Like this

    struct ContentView: View {
        var body: some View {
            
            ScrollViewReader { p in
                Form {
                    Button(action: {
                    }) {
                        Text("Top")
                    }.id(150)
                    
                    ForEach(0..<30) { index in
                        Text("\(index)")
                            .id(index)
                    }
                    Button(action: {
                        p.scrollTo(150)
                    }) {
                        Text("Scroll")
                    }
                }
            }
        }
    }