如何从父视图触发ScrollView代理



我的场景很简单,我有一个带有按钮的父视图和一个带有时间线的子视图。当我单击父视图按钮将子视图的时间轴视图移到顶部时,我想做的是。我已经能够做到这一点,但只有当按钮已经位于与时间轴视图相同的子视图中时,单击父视图按钮时,我似乎无法使其工作。如果你看看我下面的代码,按钮B是有效的,因为它与TimeLine在同一个视图中,但是我如何才能做到这一点,当我在父视图中单击按钮A时,我可以像按钮B一样将时间线移到顶部?任何建议都很好。我下面的代码也将在Xcode中工作。

struct ExampleUpdateListBind: View {

var body: some View {
VStack {
Text("Button A")
.onTapGesture {
print("By Clicking this one my timeline child view should scroll to the top")
}
.padding(.leading, 10)
MYListExamples()
}
}
}

struct MYListExamples: View {
var myList = ["X First Row","John","Abe","Joseph","Adam","John","Abe","Joseph","Adam",
"Joseph","Adam","John","Abe","Joseph","Adam","Joseph","Adam","John","Abe","Joseph","Adam"
,"Joseph","Adam","John","Abe","Joseph","Adam","Joseph","Adam","John","Abe","Joseph","Adam"
,"Joseph","Adam","John","Abe","Joseph","Adam","Joseph","Adam","John","Abe","Joseph","Adam"]
var body: some View {
let result = myList.sorted {
$0 > $1
}
ScrollViewReader { (proxy: ScrollViewProxy) in
Button("Button B") {
proxy.scrollTo(result[0], anchor: .top)
}
List {
ForEach(result) { i in
Text(i)
}
}


}

}
}

您需要在传递给子视图的父视图中保留某种状态或发布者,子视图很可能通过onChangeonReceive来观察它。

这里有一个非常简单的版本:

import SwiftUI
import Combine //possibly necessary if using a Publisher-based solution
struct ExampleUpdateListBind: View {
@State private var send = Date()

var body: some View {
VStack {
Text("Button A")
.onTapGesture {
send = Date()
}
.padding(.leading, 10)
MYListExamples(receive: send)
}
}
}

struct MYListExamples: View {
var receive : Date

var myList = ["X First Row","John","Abe","Joseph","Adam","John","Abe","Joseph","Adam",
"Joseph","Adam","John","Abe","Joseph","Adam","Joseph","Adam","John","Abe","Joseph","Adam"
,"Joseph","Adam","John","Abe","Joseph","Adam","Joseph","Adam","John","Abe","Joseph","Adam"
,"Joseph","Adam","John","Abe","Joseph","Adam","Joseph","Adam","John","Abe","Joseph","Adam"]
var body: some View {
let result = myList.sorted {
$0 > $1
}
ScrollViewReader { (proxy: ScrollViewProxy) in
Button("Button B") {
proxy.scrollTo(result[0], anchor: .top)
}
.onChange(of: receive) { _ in
proxy.scrollTo(result[0], anchor: .top)
}
List {
ForEach(result, id: .self) { I in //note that in a real-world case, we wouldn't want to use .self with strings that have duplicate values like the data provided in the original question above
Text(i)
}
}
}

}
}

其他解决方案可能包括将引用传递给发布服务器并使用onReceive,或者将状态存储在传递给子视图的ObservableObject中——无论在什么情况下,前提都是相同的。

最新更新