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

lf5gs5x2  于 2023-03-11  发布在  Swift
关注(0)|答案(1)|浏览(142)

我在SwiftUI NavigationView上有一个表单,表单没有特殊元素,只有标准元素:文本字段、日期选取器和一些按钮
我想以编程方式滚动到一个特定的元素。我该如何实现呢?
ScrollViewReader似乎不能与表单一起工作。

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

eqoofvh91#

为每个元素给予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")
                }
            }
        }
    }
}

相关问题