我有将函数传递给ChildView的ParentView,然后在ChildView中单击按钮时在ParentView中调用该函数。 但是,如果我希望孩子的孩子调用该函数怎么办?我是否需要进一步传递该功能,或者是否可以通过某种方式在整个环境中访问该功能?
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")
}
}
}
}
答案 0 :(得分:4)
是的,可以使用自定义的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")
}
}
}
}