我有 ParentView 将函数传递给 ChildView,然后当在 ChildView 中单击按钮时在 ParentView 中调用该函数。但是如果我想要 Child 的 Child 来调用该函数怎么办?我是否需要进一步向下传递该函数,或者是否有一种方法可以使函数在整个环境中以某种方式可访问?
struct ParentView: View {
func parentFunction() {
print("parentFunction called")
}
var body: some View {
ChildView(p: parentFunction)
}
}
struct ChildView: View {
var p: () -> ()
var body: some View {
VStack {
Text("child view")
Button(action: {
self.p()
}) {
Image(systemName: "person")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,可以使用自定义定义EnvironmentKey,然后使用它设置父视图环境函数,该函数将可用于所有子视图。
这是方法的演示
struct ParentFunctionKey: EnvironmentKey {
static let defaultValue: (() -> Void)? = nil
}
extension EnvironmentValues {
var parentFunction: (() -> Void)? {
get { self[ParentFunctionKey.self] }
set { self[ParentFunctionKey.self] = newValue }
}
}
struct ParentView: View {
func parentFunction() {
print("parentFunction called")
}
var body: some View {
VStack {
ChildView()
}
.environment(\.parentFunction, parentFunction) // set in parent
}
}
struct ChildView: View {
@Environment(\.parentFunction) var parentFunction // join in child
var body: some View {
VStack {
Text("child view")
Button(action: {
self.parentFunction?() // < use in child
}) {
Image(systemName: "person")
}
Divider()
SubChildView()
}
}
}
struct SubChildView: View {
@Environment(\.parentFunction) var parentFunction // join in next subchild
var body: some View {
VStack {
Text("Subchild view")
Button(action: {
self.parentFunction?() // use in next subchild
}) {
Image(systemName: "person.2")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)