是否有一种方法在父ScrollViewReader的子视图中使用scrollTo ?



我想使用子视图中的按钮滚动到父视图中的部分。在一个视图中,它是这样工作的:

import SwiftUI
struct ContentView: View {
var body: some View {
ScrollViewReader { value in
ScrollView {
Button("go to bottom") {
value.scrollTo(19)
}
ForEach(0..<20) { i in
Text("(i)")
.frame(width: 200, height: 200)
.id(i)
}
}
}
}
}

我要做的是在第二个视图中放置那个按钮,所以第一个是:

import SwiftUI
struct ContentView: View {
var body: some View {
ScrollViewReader { value in
ScrollView {
ChildButton()
ForEach(0..<20) { i in
Text("(i)")
.frame(width: 200, height: 200)
.id(i)
}
}
}
}
}

一般的(不工作的)想法是:

import SwiftUI
struct ChildButton: View {
var body: some View {
Button("go to bottom") {
value.scrollTo(19)
}
}
}

当然这不起作用,因为ChildButton不能访问'value'或ScrollViewReader。如何在子视图中调用scrollTo() ?

value传递给ChildButton

struct ContentView: View {
var body: some View {
ScrollViewReader { value in
ScrollView {
ChildButton(value: value) // <- HERE
ForEach(0..<20) { i in
Text("(i)")
.frame(width: 200, height: 200)
.id(i)
}
}
}
}
}
struct ChildButton: View {
let value: ScrollViewProxy // <- HERE
var body: some View {
Button("go to bottom") {
value.scrollTo(19)
}
}
}

最新更新