如何将表单滚动到 SwiftUI 中的特定 UI 元素

mem*_*cal 2 ios swift swiftui swiftui-form

我在 SwiftUI NavigationView 上有一个表单。该表单没有特殊元素,只有标准元素:TextField、DatePicker 和一些按钮

我想以编程方式滚动到特定元素。我怎样才能实现这个目标?

ScrollViewReader 似乎不适用于表单。

ScrollViewReader { p in
  Form {
    ....
    Button(action: {
      p.scrollTo(150)
    }) {
      Text(self.label)
    }
}
Run Code Online (Sandbox Code Playgroud)

Raj*_*han 8

为每个元素赋予 id 并将该 id 传递给.scrollTo(id)方法。像这样

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")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)